1

我有两个ActionFilterAttribute-ValidateModelStateFilterLoggingFilter

ValidateModelStateFilter我有:

 public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
            base.OnActionExecuting(actionContext);
        }
    }

用于检查 ModelState。我LoggingFilter有:

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        LogRequest(actionExecutedContext);

        base.OnActionExecuted(actionExecutedContext);

        LogRensponse(actionExecutedContext);
    }

我想记录每个请求和每个响应,即使它包含任何 ModelStateError。

现在,我的问题是:当 ModelState 无效时,它按预期返回 ErrorResponse 但日志过滤器不执行。

这是 WebApiConfig.cs 注册:

public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
        config.Filters.Add(new AuthorizeAttribute());
       // config.Filters.Add(new ValidateNullFilter());

        config.Filters.Add(new ValidateModelStateFilter());
        config.Filters.Add(new LoggingFilter());


        config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

你有什么建议我怎样才能让它工作?

4

1 回答 1

0

在您的日志过滤器中,您需要同时实现 OnActionExecuting 和 OnActionExecuted

在调用您的操作之前,将调用 OnActionExecuting 方法,您可以在其中记录请求。在您的控制器操作运行后,您的操作过滤器的 OnActionExecuted 方法将被调用,您可以在其中记录响应。

于 2015-05-25T15:51:04.173 回答