1

What is the utility of

protected internal virtual InvalidModelStateResult BadRequest(ModelStateDictionary modelState);

from public abstract class ApiController

I juts tried to us it for my Web API

if (!ModelState.IsValid)
{
   var foo = BadRequest(ModelState);
}

but nothing happens

Should I override it? And how because I can override 3 BadRequest method with different return result.

Bastien Vandamme
  • 17,659
  • 30
  • 118
  • 200
  • Use action filter like this question http://stackoverflow.com/questions/11686690/handle-modelstate-validation-in-asp-net-web-api/11724405#11724405 – cuongle Aug 25 '16 at 10:10
  • 1
    To make something happen, you're meant to `return BadRequest(...);`, just as you also might `return Ok(...);`, etc. – Damien_The_Unbeliever Aug 25 '16 at 10:13
  • Thank you Damien_The_Unbeliever. I just need to return the bad request. Now this bring me to another question. What type my API must return? object, HttpResponse that is not compatible with BadRequest that request an InvalidModelStateResult... – Bastien Vandamme Aug 25 '16 at 10:20
  • @B413, `BadRequest` inherits from `IHttpActionResult`. action should have that as its return type – Nkosi Aug 25 '16 at 10:24
  • @NKosi, And how do you deal with all my API that already return HttpResponseMessage? Is it wrong? – Bastien Vandamme Aug 25 '16 at 10:26
  • @B413, No it is not wrong. just different way of doing same thing. `BadRequest` and the others like it that are inherited from `IHttpActionResult` were added in a more recent version of the framework than `HttpResponseMessage` Under the hood they use it to create the response. – Nkosi Aug 25 '16 at 10:32
  • http://stackoverflow.com/q/21758615/196526 – Bastien Vandamme Aug 25 '16 at 11:10

1 Answers1

2

BadRequest method returns InvalidModelStateResult which is IHttpActionResult.

So it should be something you return from action

if (!ModelState.IsValid)
{
   return BadRequest(ModelState);
}

When BadRequest is used then response has 400 status code set.

Piotr Pasieka
  • 2,063
  • 1
  • 12
  • 14