how do I throw a 404 or FileNotFound exception/result from my action and let IIS use my customErrors config section to show the 404 page?
I've defined my customErrors like so
<customErrors mode="On" defaultRedirect="/trouble"> <error statusCode="404" redirect="/notfound" /> </customErrors>
My first attempt at an actionResult that tries to add this doesnt work.
public class NotFoundResult : ActionResult { public NotFoundResult() { } public override void ExecuteResult(ControllerContext context) { context.HttpContext.Response.TrySkipIisCustomErrors = false; context.HttpContext.Response.StatusCode = 404; } }
But this just shows a blank page and not my /not-found page
:(
What should I do?
You should be logging the relevant information to your error log so that you can go through it and fix the issue. If you want to show the error in the form user submitted, You may use ModelState. AddModelError method along with the Html helper methods like Html.
An ActionResult is a return type of a controller method in MVC. Action methods help us to return models to views, file streams, and also redirect to another controller's Action method.
An action result is what a controller action returns in response to a browser request. The ASP.NET MVC framework supports several types of action results including: ViewResult - Represents HTML and markup. EmptyResult - Represents no result.
What is an ActionResult? An ActionResult is a return type of a controller method, also called an action method, and serves as the base class for *Result classes. Action methods return models to views, file streams, redirect to other controllers, or whatever is necessary for the task at hand.
ASP.NET MVC 3 introduced the HttpNotFoundResult action result which should be used in preference to manually throwing the exception with the http status code. This can also be returned via the Controller.HttpNotFound method on the controller:
public ActionResult MyControllerAction() { ... if (someNotFoundCondition) { return HttpNotFound(); } }
Prior to MVC 3 you had to do the following:
throw new HttpException(404, "HTTP/1.1 404 Not Found");
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