37

I'm trying to determine the best way to implement a 404 page in a standard ASP.NET web application. I currently catch 404 errors in the Application_Error event in the Global.asax file and redirect to a friendly 404.aspx page. The problem is that the request sees a 302 redirect followed by a 404 page missing. Is there a way to bypass the redirect and respond with an immediate 404 containing the friendly error message?

Does a web crawler such as Googlebot care if the request for a non existing page returns a 302 followed by a 404?

9 Answers 9

48

Handle this in your Global.asax's OnError event:

protected void Application_Error(object sender, EventArgs e){
  // An error has occured on a .Net page.
  var serverError = Server.GetLastError() as HttpException;

  if (serverError != null){
    if (serverError.GetHttpCode() == 404){
      Server.ClearError();
      Server.Transfer("/Errors/404.aspx");
    }
  }
}

In you error page, you should ensure that you're setting the status code correctly:

// If you're running under IIS 7 in Integrated mode set use this line to override
// IIS errors:
Response.TrySkipIisCustomErrors = true;

// Set status code and message; you could also use the HttpStatusCode enum:
// System.Net.HttpStatusCode.NotFound
Response.StatusCode = 404;
Response.StatusDescription = "Page not found";

You can also handle the various other error codes in here quite nicely.

Google will generally follow the 302, and then honour the 404 status code - so you need to make sure that you return that on your error page.

10
  • Perfect. I forgot about the Server.Transfer() method. I'm already using the Application_Error event, so now I'll just call Server.Transfer() rather than Response.Redirect().
    – Ben Mills
    Mar 22, 2009 at 14:41
  • 1
    At least with IIS 7 there's not even a 302 temporary redirect with the above. The gotcha for me was discovering that Server.ClearError() is imperative for 404s (or else still did the redirect, not transfer).
    – Ted
    Oct 2, 2009 at 21:15
  • 2
    Should that 404.htm page be an .aspx page so that you can add Response.StatusCode = 404 in the code-behind?
    – codeulike
    Oct 25, 2010 at 18:56
  • @codeulike: Good catch, this was a copy from an MCMS instance, which uses an ISAPI filter to map the url to things in it's database, and so ignores the extension. The page in question did indeed have an .aspx page behind it. Oct 25, 2010 at 19:53
  • 1
    The TrySkipIisCustomErrors was exactly what I needed. Good one.
    – Ripside
    Dec 4, 2015 at 15:47
15

You can use the web.config to send 404 errors to a custom page.

    <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
        <error statusCode="403" redirect="NoAccess.htm" />
        <error statusCode="404" redirect="FileNotFound.htm" />
    </customErrors>
3
  • 1
    I tried this and it still seems to be responding with a 302 to FileNotFound.htm. Maybe the FileNotFound.htm is returned with a 404, but the initial response is still a 302 redirect. Are you seeing the same thing?
    – Ben Mills
    Mar 20, 2009 at 17:13
  • This by itself results in a 302 (at least with IIS 7). Should: 1. Do customErrors as above for 404. 2. In Application_Error (global.asax or error module) check for 404, and if so: Server.ClearError(); Server.Transfer("/page-not-found.aspx"); 3. In 404 page: Response.Status = "404 Not Found"; Response.StatusCode = 404;
    – Ted
    Oct 2, 2009 at 21:12
  • 2
    if you add redirectMode="ResponseRewrite" to the <customErrors .. redirectMode="ResponseRewrite" /> it will redirect. It will also not send the "302 Found" status code before the "404 Not Found" status code is sent. You can always check out msdn's link for this: msdn.microsoft.com/en-us/library/h0hfz6fc.aspx
    – Matt
    Feb 14, 2011 at 21:57
3

Easiest answer: don't do it in code, but configure IIS instead.

3

I also faced with 302 instead 404. I managed to fix it by doing the following:

Controller:

public ViewResult Display404NotFoundPage()
        {
            Response.StatusCode = 404;  // this line fixed it.

            return View();
        }

View:

Show some error message to user.

web.config:

<customErrors mode="On"  redirectMode="ResponseRedirect">
      <error statusCode="404" redirect="~/404NotFound/" />
</customErrors>

Lastly, the RouthConfig:

routes.MapRoute(
             name: "ErrorPage",
             url: "404NotFound/",
             defaults: new { controller = "Pages", action = "Display404NotFoundPage" }
         );
3

I really like this approach: it creates a single view to handle all error types and overrides IIS.

[1]: Remove all 'customErrors' & 'httpErrors' from Web.config

[2]: Check 'App_Start/FilterConfig.cs' looks like this:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }
}

[3]: in 'Global.asax' add this method:

public void Application_Error(Object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    Server.ClearError();

    var routeData = new RouteData();
    routeData.Values.Add("controller", "ErrorPage");
    routeData.Values.Add("action", "Error");
    routeData.Values.Add("exception", exception);

    if (exception.GetType() == typeof(HttpException))
    {
        routeData.Values.Add("statusCode", ((HttpException)exception).GetHttpCode());
    }
    else
    {
        routeData.Values.Add("statusCode", 500);
    }

    Response.TrySkipIisCustomErrors = true;
    IController controller = new ErrorPageController();
    controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
    Response.End();
}

[4]: Add 'Controllers/ErrorPageController.cs'

public class ErrorPageController : Controller
{
    public ActionResult Error(int statusCode, Exception exception)
    {
        Response.StatusCode = statusCode;
        ViewBag.StatusCode = statusCode + " Error";
        return View();
    }
}

[5]: in 'Views/Shared/Error.cshtml'

@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = (!String.IsNullOrEmpty(ViewBag.StatusCode)) ? ViewBag.StatusCode : "500 Error";
}

 <h1 class="error">@(!String.IsNullOrEmpty(ViewBag.StatusCode) ? ViewBag.StatusCode : "500 Error"):</h1>


//@Model.ActionName
//@Model.ContollerName
//@Model.Exception.Message
//@Model.Exception.StackTrace

:D

1
2

Do you use this anywhere?

 Response.Status="404 Page Not Found"
2

I can see that setting up the 404 page in the web.config is a nice clean method, BUT it still initially responds with a 302 redirect to the error page. As an example, if you navigate to:

https://stackoverflow.com/x.aspx

you'll be redirected via a 302 redirect to:

https://stackoverflow.com/404?aspxerrorpath=/x.aspx

What I want to happen is this:

http://www.cnn.com/x.aspx

There's no redirect. A request for the missing URL returns a 404 status code with a friendly error message.

0

You can configure IIS itself to return specific pages in response to any type of http error (404 included).

0

I think the best way is to use the custom errors construct in your web.config like below, this let's you wire up pages to handle all of the different HTTP codes in a simple effective manner.

  <customErrors mode="On" defaultRedirect="~/500.aspx">
     <error statusCode="404" redirect="~/404.aspx" />
     <error statusCode="500" redirect="~/500.aspx" />
  </customErrors>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.