我如何使用操作筛选集中的ModelState验证在asp.net mvc的? [英] How can I centralize modelstate validation in asp.net mvc using action filters?

查看:113
本文介绍了我如何使用操作筛选集中的ModelState验证在asp.net mvc的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我写这篇code在几个地方,总是重复这样的逻辑:

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

public ActionResult MyMethod(MyModel collection)
{
    if (!ModelState.IsValid)
    {
        return Json(false);//to read it from javascript, it's always equal
    }
    else
    {
        try
        {
            //logic here
            return Json(true);//or Json(false);
        }
        catch
        {
            return Json(false);//to read it from javascript, it's always equal
        }
    }
}

有没有使用动作过滤器,不能重复的try-catch 的任何方式,请问如果模型是有效的和返回JSON(假)的ActionResult

Is there any way using action filters, not to be repeating the try-catch, ask if the model is valid and return Json(false) as ActionResult?

推荐答案

要使用REST接轨,应返回的 HTTP错误的请求400 ,以表明请求的格式不正确 (型号是无效的),而不是返回 JSON(假)

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).

尝试从这个属性<一个href=\"http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api\">asp.net用于Web API官方网站:

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

一个为asp.net mvc的版本可能是这样的:

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 == false)
              {
                   filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
              }
        }
}

这篇关于我如何使用操作筛选集中的ModelState验证在asp.net mvc的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆