How to show custom 404 page in ASP.NET without redirecting?

When in ASP.NET for IIS 7, the request is 404, I want the custom error page to display. The URL in the address bar should not be changed, so redirects are not required. How can i do this?

+3
source share
4 answers

In the OnError event of your application, you can test HttpExceptions with a status code of 404, and then execute Server.Transfer on your custom 404 page instead of Response.Redirect. Take a look at http://blog.dmbcllc.com/2009/03/02/aspnet-application_error-detecting-404s/

+2
source

ASP.NET, customErrors web.config redirectMode = "ResponseRewrite".

<customErrors mode="On" redirectMode="ResponseRewrite">
  <error statusCode="404" redirect="/404.aspx" />
</customErrors>

. Server.Transfer(), -. MVC.

+5

http- . , 404s, web.config , , .

public class CustomErrorsTransferModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.Error += Application_Error;
    }

    public void Dispose()  {  }

    private void Application_Error(object sender, EventArgs e)
    {
        var error = Server.GetLastError();
        var httpException = error as HttpException;
        if (httpException == null)
            return;

        var section = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection;
        if (section == null)
            return;

        if (!AreCustomErrorsEnabledForCurrentRequest(section))
            return;

        var statusCode = httpException.GetHttpCode();
        var customError = section.Errors[statusCode.ToString()];

        Response.Clear();
        Response.StatusCode = statusCode;

        if (customError != null)
            Server.Transfer(customError.Redirect);
        else if (!string.IsNullOrEmpty(section.DefaultRedirect))
            Server.Transfer(section.DefaultRedirect);
    }

    private bool AreCustomErrorsEnabledForCurrentRequest(CustomErrorsSection section)
    {
        return section.Mode == CustomErrorsMode.On ||
               (section.Mode == CustomErrorsMode.RemoteOnly && !Context.Request.IsLocal);
    }

    private HttpResponse Response
    {
        get { return Context.Response; }
    }

    private HttpServerUtility Server
    {
        get { return Context.Server; }
    }

    private HttpContext Context
    {
        get { return HttpContext.Current; }
    }
}

web.config ,

<httpModules>
     ...
     <add name="CustomErrorsTransferModule" type="WebSite.CustomErrorsTransferModule, WebSite" />
     ...
</httpModules>
+1

Server.Transfer("404error.aspx")
-1

Source: https://habr.com/ru/post/1716685/


All Articles