Asp.net web api 具有空参数的ModelState无效

Asp.net web api 具有空参数的ModelState无效,asp.net-web-api,Asp.net Web Api,正在使用新的WebAPI 2.0 RC1预发布位。。。鉴于此方法: [HttpPut("{sampleForm}/{id?}")] public HttpResponseMessage PutSampleForm(SampleForm sampleForm, int? id) { if (!ModelState.IsValid) { // handle invalid model } // Insert valid model into DB w

正在使用新的WebAPI 2.0 RC1预发布位。。。鉴于此方法:

[HttpPut("{sampleForm}/{id?}")]
public HttpResponseMessage PutSampleForm(SampleForm sampleForm, int? id)
{
    if (!ModelState.IsValid)
    {
        // handle invalid model
    }

    // Insert valid model into DB with EF

    return Request.CreateResponse(HttpStatusCode.OK);
}

它被标记为可空id,但如果id实际上为空,则ModelState也被标记为无效。。。这是预期的,还是我可以做些什么让ModelState知道它需要忽略可为空的参数?

是的,您也可以在模型的属性上使用问号,如下所示:

private int? id {get; set;}

但这是一个传递参数,不是我模型的一部分。。。也许我需要深入研究是什么定义了模型,从中确定了模型状态。什么是sampleForm?您应该将模型传递给控制器而不是SampleForm是我的模型,并且是复杂类型。然而,id不是该模型的一部分。这看起来像是RC位中的一个bug。不过,可选路由变量的行为在后RC位中发生了变化。在后RC位中,您需要将操作上的参数设置为
int?id=null
否则路由将不匹配,导致404。对于您当前的场景,我能想到的解决方法是专门检查
id