C# WebApi获取The parameters dictionary contains a null entry错误

C# WebApi getting The parameters dictionary contains a null entry error

有以下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=The parameters dictionary contains a null entry for parameter 'CustomerId' of non-nullable type 'System.Int64' for method 'System.Threading.Tasks.Task1[System.Web.Http.IHttpActionResult] GetById(Int64, System.Nullable1[System.Int64])' in '....'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

[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
}

谁能帮忙解决这个问题?或者纠正我我做错了什么?

可选参数应该用作模板的结尾,因为它们可以从 url.

中排除

此外,通过对客户 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
}