2017-02-15 19 views
1

有下列API方法:C#的WebAPI得到的參數字典包含空輸入錯誤

[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.Task 1[System.Web.Http.IHttpActionResult] GetById(Int64, System.Nullable 1[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 
} 

誰能幫助如何解決這個問題?或者糾正我我做錯了什麼?

回答

1

可選參數應該用作模板的結尾,因爲它們可以從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 
} 
+0

感謝。在我的情況下,CustomerId應該很長? 。它會使用可空的long嗎? –

+0

不,因爲您不能在可選參數後面顯示細分。 – Nkosi

相關問題