提问者:小点点

MVC5/API2自定义ActionFilterAttribute OnActionExecuting中的CreateErrorResponse


使用MVC4,我能够创建并注册一个全局操作过滤器,它将在操作执行之前检查模型状态,并在任何损坏发生之前返回序列化的

public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
    if (!actionContext.ModelState.IsValid)
    {
        actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
    }
}

null

public override void OnActionExecuting(ActionExecutingContext nActionExecutingContext)
{
    if (!nActionExecutingContext.Controller.ViewData.ModelState.IsValid)
    {
        nActionExecutingContext.Result = // Where is Request.CreateErrorResponse ?
    }
}

null

null


共1个答案

匿名用户

必须

using System.Net.Http;

而不是

using System.Web.Http;

那么这就起作用了:

using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

public class ValidateModelStateAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            actionContext.Response = actionContext.ControllerContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
        }
    }
}