I am writing a web api in a .net core web project.
// POST: api/Companies
[HttpPost]
public void Post([FromBody]string value)
{
if (string.IsNullOrEmpty(value))
{
// inform the client that request is incorrect.
}
}
I want to be able to inform the client that its a bad request, I found many articles but all were 1-2 years old, I am sure a lot has changed since then. So wanted to know the best solution for this problem.
The BadRequest method, declared in the ControllerBase class, will create a 400 response message. It's been around for years (new versions, almost same implementation) and it's solid, so use that
[HttpPost]
public IActionResult Post([FromBody]string value)
{
if (string.IsNullOrEmpty(value))
{
return BadRequest("request is incorrect");
}
}
The recommended way to do this is by changing your method signature to:
[HttpPost]
public IHttpActionResult Post([FromBody]string value)
{
if (string.IsNullOrEmpty(value))
{
return BadRequest("Value must be passed in the request body.");
}
else
{
return Ok("Request was correct");
}
}
By returning a IHttpActionResult you can call the Ok(...) method
, the BadRequest("reason")
, and other built-in types like you can find on the HttpActionResult documentation page
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With