VAAA
VAAA

Reputation: 15039

WebAPI HttpActionExecutedContext get controller name

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

Upvotes: 28

Views: 13700

Answers (1)

VAAA
VAAA

Reputation: 15039

Finally I found it:

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

Thanks

Upvotes: 62

Related Questions