可空参数的Web API验证失败 [英] Web api validation on nullable parameter fails

查看:85
本文介绍了可空参数的Web API验证失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证一种非常简单的方法,并且我得到的值'null'对于Nullable'1错误无效。

I am trying to validate very simple method and I am getting The value 'null' is not valid for Nullable`1 error.

    [ValidateModel]
    public IEnumerable<SomeData> Get(bool? showExtra = null)
    {
        return this.MockDataManager.ShowData(showExtra);
    }

ValidateModel属性为:

ValidateModel property is:

 public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext != null && actionContext.ModelState.IsValid == false)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);
        }
    }

现在,如果我使用/ true和/调用方法虚假的作品。如果我使用/调用方法,但如果使用/ null调用方法,它也将起作用,但验证失败并显示错误消息 null值对于Nullable`1无效。
如何解决这个问题?

Now, if i call method with /true and /false it works. Also it works if I call method with / but if i call it with /null validation fails and error message The value 'null' is not valid for Nullable`1 appears. How to resolve this?

推荐答案

用/调用是解决方法。

Calling it with / is the way to go. Calling it for /null is not what you want to do.

这是幕后发生的事情:

/false
OK, let's see if I can convert that into a bool. Yes, I can.

/true
OK, let's see if I can convert that into a bool. Yes, I can.

/
OK, let's see if I can convert that into a bool. No, I can't, so use the default
value specified in the method arguments.

/null
OK, let's see if I can convert that into a bool. No, I can't, so throw an
exception.

这篇关于可空参数的Web API验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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