Have the following api method:
[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
}
when I try http://localhost/Customers/Search/keyword
, the following works but
when I try http://localhost/Customers/Search
, I am getting following error:
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
}
Can anyone help how to fix the issue? Or correct me what am i doing wrong?
Optional parameter should be used as the end of the template as they can be excluded from the url.
Also by using a route constraint for the customer id you will make sure that a key word is not mistaken for a customer id.
Reference: 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
}