[ACCEPTED]-Best way to implement a 404 in ASP.NET-http-status-code-404

Accepted answer
Score: 48

Handle this in your Global.asax's OnError 7 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 6 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 5 can also handle the various other error 4 codes in here quite nicely.

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

Score: 15

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

    <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
        <error statusCode="403" redirect="NoAccess.htm" />
        <error statusCode="404" redirect="FileNotFound.htm" />
    </customErrors>
Score: 3

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

Score: 3

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

Controller:

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

            return View();
        }

View:

Show some 1 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" }
         );
Score: 3

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

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

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

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

[3]: in 'Global.asax' add this 2 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 1 '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

Score: 2

Do you use this anywhere?

 Response.Status="404 Page Not Found"

0

Score: 2

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

https://stackoverflow.com/x.aspx

you'll be redirected via a 302 4 redirect to:

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

What I want to happen is this:

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

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

Score: 0

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

Score: 0

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

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

More Related questions