1

我正在尝试验证非常简单的方法,但我得到 The value 'null' is not valid for Nullable`1 错误。

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

ValidateModel 属性是:

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

现在,如果我用 /true 和 /false 调用方法,它就可以工作。如果我用 / 调用方法,它也可以工作,但如果我用 /null 调用它验证失败并且错误消息 The value 'null' is not valid for Nullable`1 出现。如何解决这个问题?

4

1 回答 1

3

用 / 调用它是要走的路。为 /null 调用它不是您想要做的。

以下是幕后发生的事情:

/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.
于 2013-10-07T11:57:59.357 回答