Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET core web api send bad request to client

Tags:

asp.net-core

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.

like image 729
Yasser Shaikh Avatar asked Aug 25 '18 11:08

Yasser Shaikh


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");
    }
}
like image 52
Marcus Höglund Avatar answered Oct 12 '22 14:10

Marcus Höglund


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

like image 36
Erik J. Avatar answered Oct 12 '22 13:10

Erik J.