14

I'm writing an api controller in ASP 5. I want to return a bad request code exception if the parameters passed to the service are incorrect. In the current version of webapi I would do:

throw new HttpResponseException(HttpStatusCode.BadRequest);

However HttpResponseException is part of System.Web, which has been removed from ASP 5 and thus I cannot instantiate it anymore.

What is the proper way to do this in vNext?

n8mob
  • 266
  • 2
  • 9
CybrGaunt
  • 139
  • 1
  • 4
  • 1
    Take a look at http://www.strathweb.com/2015/01/migrating-asp-net-web-api-mvc-6-exploring-web-api-compatibility-shim/. – DWright Apr 16 '15 at 02:18

1 Answers1

8

To answer your question, you can use the WebApiCompatibilityShim which ports HttpResponseException (and many other features) forward into MVC 6. (thanks to DWright for the link to that article.)

It seems like the MVC-6 way to do it is to return an IActionResponse from your method and then call HttpBadRequest() which is a method on the base Microsoft.AspNet.Mvc.Controller class that returns an BadRequestResult, which I believe is the best way to get a 400 status into the response.

The Controller class has methods for other response codes as well - including the HttpNotFound() method which causes a 404 to be returned.

See also: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api

n8mob
  • 266
  • 2
  • 9
  • This is accurate. FWIW, the OP seems to be looking for a 400 and not a 404, thus `return HttpBadRequest()`. And came here looking for a 401, or `return HttpUnauthorized()`. – lc. Apr 25 '16 at 06:36
  • Thanks, @lc. - I didn't notice the discrepancy. I edited my response. – n8mob Apr 29 '16 at 19:55
  • The link for the WebApiCompatibilitySim is dead. Also, could you comment on how we're supposed to respond to basic RESTful requests with MVC5 (which, even in the generated template, are 'void' methods). – Quark Soup Jun 09 '17 at 19:00