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?
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://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With