29

I may encounter situations, when I need to just return bad request result.

For example, there is a call to MVC 3 site's controllers action, but the required parameter is missing in a request uri.

What do I return in response. I know I can do this:

Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Content(string.Empty);

Is this the correct way for the above described situation?

Maxim V. Pavlov
  • 10,303
  • 17
  • 74
  • 174

1 Answers1

38

Your solution will work OK, but more clear way will be using HttpStatusCodeResult class, like this:

return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
Bryan Legend
  • 6,790
  • 1
  • 59
  • 60
Sergey Kudriavtsev
  • 10,328
  • 4
  • 43
  • 68
  • 4
    No need to cast the status code to an int. Just do return new HttpStatusCodeResult(HttpStatusCode.BadRequest); – iheartcsharp Aug 15 '13 at 15:37
  • 14
    This solution is not equivalent for author's code. By default HttpStatusCodeResult causes IIS to return default HTML error page with error description, but not empty content. – dlxeon Mar 18 '14 at 06:50
  • 1
    @dlxeon :to get an empty result, we can use NoContent Status instead of BadRequest. Then it should look like this. HttpStatusCodeResult(HttpStatusCode.NoContent); – PNP Jul 09 '21 at 09:26