1

I am trying to throw a simple HttpException 404 error from code behind in a class in MVC asp.net core 2 web application.

Cœur
  • 37,241
  • 25
  • 195
  • 267
J.P.
  • 21
  • 5

2 Answers2

0

From documentation you could use StatusCodeResultas the result:

public StatusCodeResult StatusCodeActionResult()
{
    return StatusCode(404);
}

For more information see StatusCodeResult

OlafW
  • 700
  • 6
  • 22
  • This is for a Contoller class. I want to send back to the browser a 404 error code from a class dirived from RequestCultureProvider. – J.P. Jan 17 '18 at 10:01
  • Well, it seems that the `RequestCultureProvider` is not designed to return something else than a `ProviderCultureResult` so maybe this [link](https://stackoverflow.com/questions/31054012/asp-net-5-mvc-6-equivalent-of-httpexception) could give you an idea - it simply creates an own `HttpException` and throws it. Or you will need to see whether `this` offers you access to the `Response` so you can set header tags manually? – OlafW Jan 17 '18 at 10:20
  • I have tried to use the Response.StatusCode but Response.End() has been removed from core 2 – J.P. Jan 17 '18 at 10:31
0

I created a middleware to handle custom exceptions but I think that’s not the best performance wise approach since core team says it’s not a good practice to throw exception to handle business logic. You can see the link from OlafW comments

J.P.
  • 21
  • 5