使用MVC4,我能够创建并注册一个全局动作过滤器,该过滤器将在动作执行之前检查模型状态,并在任何损坏发生之前返回序列化的ModelState
。
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
然而,使用MVC5,我无法找到Request
因此CreateErrorResponse
public override void OnActionExecuting(ActionExecutingContext nActionExecutingContext)
{
if (!nActionExecutingContext.Controller.ViewData.ModelState.IsValid)
{
nActionExecutingContext.Result = // Where is Request.CreateErrorResponse ?
}
}
我意识到我可以创建一个自定义响应类来分配给Result
,但如果CreateErrorResponse
仍然可用,我宁愿使用内置的。
我想知道哪些地方相对于MVC5 / Web API 2中的ActionExecutingContext
?
答案 0 :(得分:-2)
根据this回答,您的解决方案是:
using System.Web.Mvc;
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.Controller.ViewData.ModelState.IsValid)
{
// This (contain view data and validation error in the form):
filterContext.Result = new ViewResult()
{
ViewData = filterContext.Controller.ViewData,
ViewName = filterContext.ActionDescriptor.ActionName
};
// Or this (just redirect to requested action):
filterContext.Result = new RedirectResult(filterContext.ActionDescriptor.ActionName);
// Or this (just add http status code):
filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
}
}
答案 1 :(得分:-2)
必须
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);
}
}
}