Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

throwing/returning a 404 actionresult or exception in Asp.net MVC and letting IIS handle it

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?

like image 276
CVertex Avatar asked Jan 04 '10 08:01

CVertex


People also ask

How do I return an error in ActionResult?

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.

What is ActionResult return type in MVC?

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.

What is ActionResult in ASP NET MVC?

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 ActionResult function?

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.


1 Answers

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"); 
like image 150
Rob Levine Avatar answered Sep 27 '22 21:09

Rob Levine