C#WebApi获取参数字典包含空条目错误

时间:2017-02-15 11:41:52

标签: c# c#-4.0 asp.net-web-api2 asp.net-web-api-routing

有以下api方法:

[HttpPut]
[Route("Customers/{CustomerId}/Search", Name = "CustomerSearch")]
[ResponseType(typeof(SearchResults))]
public async Task<IHttpActionResult> Search([FromBody]SearchFilters filters, long? CustomerId = null)
{
    //This func searches for some subentity inside customers
}

当我尝试http://localhost/Customers/Search/keyword时,以下工作正常 当我尝试http://localhost/Customers/Search时,我收到了以下错误:

  

messageDetail =参数字典包含空条目   参数&#39; CustomerId&#39;非可空类型的System.Int64&#39;方法   &#39; {System.Threading.Tasks.Task {1}} 1 [System.Int64])&#39;在&#39; ....&#39;。一个   可选参数必须是引用类型,可空类型或be   声明为可选参数。

1[System.Web.Http.IHttpActionResult]
  GetById(Int64, System.Nullable

任何人都可以帮忙解决问题吗?或者纠正我,我做错了什么?

1 个答案:

答案 0 :(得分:1)

可选参数应该用作模板的末尾,因为它们可以从网址中排除。

此外,通过对客户ID使用路由约束,您将确保关键字不会被误认为是客户ID。

参考:Attribute Routing in ASP.NET Web API 2

//PUT Customers/10/Search
[HttpPut]
[Route("Customers/{CustomerId:long}/Search", Name = "CustomerSearch")]
[ResponseType(typeof(SearchResults))]
public async Task<IHttpActionResult> Search(long CustomerId, [FromBody]SearchFilters filters, ) {
    //This func searches for some subentity inside customers
}

//GET Customers/Search    
//GET Customers/Search/keyword
[HttpGet]
[Route("Customers/Search/{keyword?}", Name = "GetCustomersByKeyword")]
public async Task<IHttpActionResult> SearchCustomers(string keyword = "") {
    //This func searches for customers based on the keyword in the customer name
}