1

I have a controller in my MVC 6 API project. There is a post method and what I want is to validate posted value and return some error back to a client if data are not valid.

[HttpPost]
public void Post([FromBody]PostedHistoricalEvent value)
{
    if (!IsHistoricalEventValid(value))
    {
       //return error status code
    }
}

Now I wonder why Post method in the default template does not have any returning type but void and how then one should return an error http status code with some message?

alexxjk
  • 1,681
  • 5
  • 18
  • 30

1 Answers1

2

An action method that has no return type (void) will return an EmptyResult, or an 200 OK without a response body.

If you want to alter the response, then you can either change the return type and return an HttpStatusCodeResult:

public IActionResult Post(...)
{
    // ...
    return new HttpStatusCodeResult(400);
}

Or set it on the Controller.Response:

public void Post(...)
{
    // ...
    Response.StatusCode = 400;
}
Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272