ASP.NET Web API ActionFilter example

后端 未结 2 1306
情话喂你
情话喂你 2020-12-02 16:21

I\'m new to the whole MVC thing and am looking at re-implementing some WCF services using ASP.NET Web API. As part of that, I\'d like to implement an action filter that log

相关标签:
2条回答
  • 2020-12-02 17:08

    You have to be sure your code uses the ActionFilterAttribute from the System.Web.Http.Filters namespace and not the one from System.Web.Mvc.

    So please check that you have

     using System.Web.Http.Filters;
    
    0 讨论(0)
  • 2020-12-02 17:19

    As Sander mentioned I tried the below code, its action filter is getting executed.

    public class WebAPIActionFilterAttribute : System.Web.Http.Filters.ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            PersonController.Messages.Add("OnActionExecuted");
        }
    
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            PersonController.Messages.Add("OnActionExecuting");
        }
    }
    
    public class WebAPIExceptionFilter : System.Web.Http.Filters.ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            PersonController.Messages.Add("OnException");
            actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent("Something went wrong") };
        }
    }
    

    PersonController.Messages is a static string list. if you want to check whether OnActionExecuted is getting executed or not, you may call the same API method again, you would see the "OnActionExecuted" in the Messages list.

    0 讨论(0)
提交回复
热议问题