.NET core web api send bad request to client

Viewed 25510

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.

2 Answers

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

Related