加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何使用动作过滤器在asp.net mvc中集中模型验证?

发布时间:2020-12-15 03:53:03 所属栏目:百科 来源:网络整理
导读:我在几个地方写这个代码,总是重复这个逻辑: 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 Jso
我在几个地方写这个代码,总是重复这个逻辑:
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(false)作为ActionResult?

解决方法

为了符合REST,您应该返回http错误请求400以指示请求格式错误(模型无效),而不是返回Json(false).

尝试这个属性从asp.net official site为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的版本可能是这样的:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读