Web api validation on nullable parameter fails

你。 提交于 2019-12-02 18:13:40

问题


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 property is:

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

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?


回答1:


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

Here's what is happening behind the scenes:

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


来源:https://stackoverflow.com/questions/19221733/web-api-validation-on-nullable-parameter-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!