Throw / return a 404 actionresult or exception in MVC Asp.net and let IIS handle it

how do I remove exception / result 404 or FileNotFound from my action and let IIS use my customErrors configuration configuration to show page 404?

I defined my custom errors as such

<customErrors mode="On" defaultRedirect="/trouble"> <error statusCode="404" redirect="/notfound" /> </customErrors> 

My first attempt at actionResult that tries to add this does not work.

 public class NotFoundResult : ActionResult { public NotFoundResult() { } public override void ExecuteResult(ControllerContext context) { context.HttpContext.Response.TrySkipIisCustomErrors = false; context.HttpContext.Response.StatusCode = 404; } } 

But it just shows a blank page, not my / not found page

: (

What should I do?

+42
asp.net-mvc iis-7
Jan 04 '10 at 8:58
source share
3 answers

ASP.NET MVC 3 introduced the result of the HttpNotFoundResult action, which should be used as the preferred way to manually throw an exception with the http status code. This can also be returned using the Controller.HttpNotFound method on the controller:

 public ActionResult MyControllerAction() { ... if (someNotFoundCondition) { return HttpNotFound(); } } 

Before MVC 3, you had to do the following:

 throw new HttpException(404, "HTTP/1.1 404 Not Found"); 
+124
Jan 04 '10 at 9:47
source share

You can call Controller.HttpNotFound

http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.httpnotfound(v=vs.98).aspx

 if (model == null) { return HttpNotFound(); } 
+6
Jun 26 2018-12-12T00:
source share
+2
Feb 17 '11 at 16:25
source share



All Articles