Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you throw HttpResponseException in ASP 5 (vnext)

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?

like image 585
CybrGaunt Avatar asked Apr 16 '15 00:04

CybrGaunt


1 Answers

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

like image 136
n8mob Avatar answered Oct 08 '22 09:10

n8mob