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 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 Answer 1

3

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.
Sign up to request clarification or add additional context in comments.

2 Comments

I thought that this is the way - than you for great explanation!
No problem. The only other way to do it if you absolutely needed the /null segment in your URL would be to change the method argument from bool? to string and manually parse it into a bool? in the method body. The reason is that WebAPI is treating null as a value rather than the absence of a value, which is what null really is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.