سؤال

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?

هل كانت مفيدة؟

المحلول

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.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top