In MVC 5 you could throw a HttpException with a HTTP code and this would set the response like so:
throw new HttpException((int)HttpStatusCode.BadRequest, "Bad Request.");
HttpException does not exist in ASP.NET 5 / MVC 6. What is the equivalent code?
Alternatively, if you just want to return an arbitrary status code and aren't concerned with the Exception-based approach, you can use
Update: as of .NET Core RC 2, the Http prefix is dropped. It is now:
The
Microsoft.AspNet.Mvc.Controller
base class exposes aHttpBadRequest(string)
overload which takes an error message to return to the client. So from within a controller action, you could call:Ultimately my nose says any private methods called from within a controller action should either be fully http-context-aware and return an
IActionResult
, or perform some other small task completely isolated from the fact that it's inside of an http pipeline. Granted this is my personal opinion, but a class that performs some piece of business logic should not be returning HTTP status codes, and instead should be throwing its own exceptions which can be caught and translated at the controller/action level.I implemented my own
HttpException
and supporting middleware which catches allHttpException
's and turns them into the corresponding error response. A short extract can be seen below:You can use the Boilerplate.AspNetCore Nuget package or you can view the full source code on the following ASP.NET MVC Boilerplate GitHub project, or create a new project using the ASP.NET MVC Boilerplate project template which lets you optionally turn on this feature when creating a new project (just check the box, to turn it on).
After a brief chat with @davidfowl, it seems that ASP.NET 5 has no such notion of
HttpException
orHttpResponseException
that "magically" turn to response messages.What you can do, is hook into the ASP.NET 5 pipeline via MiddleWare, and create one that handles the exceptions for you.
Here is an example from the source code of their error handler middleware which will set the response status code to 500 in case of an exception further up the pipeline:
And you need to register it with
StartUp.cs
: