Reputation: 37115
I have the following controlelr in my Web-API-project:
// GET: api/Medikamente/search/Name/Ibuprophen
[HttpGet("search/Name/{name}")]
public async Task<ActionResult<IEnumerable<Medikament>>> Search(string name)
{
return this._context.Medikament
.Where(x => x.Name.Contains(name))
.ToList();
}
When I use https://localhost/api/mycontroller/search/Name/whatever
everything works as intended and I get a collection of Medikament
s. However when I provide an empty string, I get an HTTP-error:
"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"One or more validation errors occurred.","status":400,"errors":{"name":["The name field is required."]},"traceId":"00-c02c1d252f699ee6612dc4b7d4ac29c7-20f9167159656762-00"}
The same applies when I omit the parameter completely:
https://localhost/mycontroller/search/Name/
How do I provide an empty string to the controller?
Upvotes: 0
Views: 61
Reputation: 503
You have to set the request parameter name to nullable to allow empty string or null values.
// GET: api/Medikamente/search/Name/Ibuprophen
[HttpGet("search/Name/{name}")]
public async Task<ActionResult<IEnumerable<Medikament>>> Search(string? name)
{
return this._context.Medikament
.Where(x => x.Name.Contains(name))
.ToList();
}
Still, it's not working then also set route parameter to nullable also.
// GET: api/Medikamente/search/Name/Ibuprophen
[HttpGet("search/Name/{name?}")]
public async Task<ActionResult<IEnumerable<Medikament>>> Search(string? name)
{
return this._context.Medikament
.Where(x => x.Name.Contains(name))
.ToList();
}
Upvotes: 0