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

asp.net MvcHttpIis 7

asp.net Mvc Problem Overview


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?

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

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");

Solution 2 - asp.net Mvc

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();
}

Solution 3 - asp.net Mvc

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCVertexView Question on Stackoverflow
Solution 1 - asp.net MvcRob LevineView Answer on Stackoverflow
Solution 2 - asp.net MvcSimonView Answer on Stackoverflow
Solution 3 - asp.net MvctugberkView Answer on Stackoverflow