How can I centralize modelstate validation in asp.net mvc using action filters?

后端 未结 4 1830
一生所求
一生所求 2020-12-05 01:11

I write this code in several places and always repeat this logic:

public ActionResult MyMethod(MyModel collection)
{
    if (!ModelState.IsValid)
    {
              


        
4条回答
  •  攒了一身酷
    2020-12-05 01:13

    To conform with REST, you should return http bad request 400 to indicate that the request is malformed (model is invalid) instead of returning Json(false).

    Try this attribute from asp.net official site for web api:

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

    A version for asp.net mvc could be like this:

    public class ValidateModelAttribute : ActionFilterAttribute
    {
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                  if (!filterContext.Controller.ViewData.ModelState.IsValid)
                  {
                       filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
                  }
            }
    }
    

提交回复
热议问题