【问题标题】:Web api validation on nullable parameter fails可空参数的 Web api 验证失败
【发布时间】:2013-10-07 09:54:35
【问题描述】:

我正在尝试验证非常简单的方法,但出现 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 出现。 如何解决?

【问题讨论】:

    标签: validation asp.net-web-api data-annotations action-filter


    【解决方案1】:

    用 / 调用它是可行的方法。为 /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.
    

    【讨论】:

    • 我认为这就是方式 - 比你解释得好!
    • 没问题。如果您绝对需要 URL 中的 /null 段,唯一的另一种方法是将方法参数从 bool? 更改为 string 并手动将其解析为方法主体中的 bool?。原因是 WebAPI 将 null 视为一个值,而不是缺少一个值,这正是 null 的真正含义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 2019-05-16
    • 2020-08-17
    • 1970-01-01
    相关资源
    最近更新 更多