WebAPI HttpActionExecutedContext get controller name

VAAA picture VAAA · Aug 14, 2014 · Viewed 11.8k times · Source

I need to get the controller who triggers a filter attribute.

I have the following filter:

public override void OnException(HttpActionExecutedContext filterContext) {
    if (filterContext == null) {
        throw new ArgumentNullException("filterContext");
    }


    if (filterContext.Exception != null) {

        // string controllerName = (string) filterContext.....??

        // string actionName = (string) filterContext.....?

        HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.InternalServerError) {
            Content = new StringContent("An unhandled exception was thrown by Customer Web API controller."),
                ReasonPhrase = "An unhandled exception was thrown by Customer Web API controller."
        };

        filterContext.Response = msg;


    }

}

In traditional MVC this was easy by doing:

string controllerName = (string) filterContext.RouteData.Values["controller"];
string actionName = (string) filterContext.RouteData.Values["action"];

Any clue? Appreciate it

Answer

VAAA picture VAAA · Aug 14, 2014

Finally I found it:

filterContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName
filterContext.ActionContext.ActionDescriptor.ActionName

Thanks