动作参数的必填属性无效 [英] Required attribute on action parameter doesn't work

查看:75
本文介绍了动作参数的必填属性无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码类似于:

[HttpPost]
public ResultEntityVM Register([FromBody,Required] RegisterParam createAssessorParam)
{
    if (ModelState.IsValid == false)
    {
        return null;
    }

    //other code
    ResultEntityVM vm = new ResultEntityVM();
    return vm;
}

当参数 createAssessorParam null 时, ModelState.IsValid 的值为 true .为什么?

When the parameter createAssessorParam is null, the value of ModelState.IsValid is true. Why?

如果我想自动判断参数是否为 null ,我该怎么办?我不能只写代码:

If I want to auto judge the parameter is null or not, what can I do? Don't I can only write the code:

if(RegisterParam  != null)
{
   //other
}

推荐答案

我遇到了同样的问题,并通过实现一个自定义操作过滤器属性来解决此问题,该属性评估了操作方法参数的所有验证属性.

I've run into the same problem and solved it by implementing a custom action filter attribute evaluating all the validation attributes of the action method parameters.

我在此博客文章,我在这里使用ASP.NET Core 1.0,但同样的方法也应在ASP.NET 4中使用.

I described the approach in this blog post, where I use ASP.NET Core 1.0, but the same approach should work with ASP.NET 4 as well.

这篇关于动作参数的必填属性无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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