C# 如何在ASP.NET中显示自定义404页面而无需重定向?

C# 如何在ASP.NET中显示自定义404页面而无需重定向?,c#,.net,asp.net,asp.net-mvc,vb.net,C#,.net,Asp.net,Asp.net Mvc,Vb.net,当IIS 7上ASP.NET中的请求为404时,我希望显示自定义错误页面。地址栏中的URL不应更改,因此没有重定向。我怎样才能做到这一点?您可以使用 Server.Transfer("404error.aspx") 我使用http模块来处理这个问题。它适用于其他类型的错误,而不仅仅是404,并允许您继续使用CustomErrors web.config部分来配置显示的页面 public class CustomErrorsTransferModule : IHttpModule { p

当IIS 7上ASP.NET中的请求为404时,我希望显示自定义错误页面。地址栏中的URL不应更改,因此没有重定向。我怎样才能做到这一点?

您可以使用

Server.Transfer("404error.aspx")

我使用http模块来处理这个问题。它适用于其他类型的错误,而不仅仅是404,并允许您继续使用CustomErrors 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>

...
...

作为通用ASP.NET解决方案,在web.config的customErrors部分中,添加redirectMode=“ResponseWrite”属性

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


注意:这在内部使用Server.Transfer(),因此重定向必须是Web服务器上的实际文件。这不可能是MVC路由。

您有很多标记-这是webforms还是MVC?注意,这是在3.5 SP1中添加的。我有一个网页抛出InvalidOperationException,导致返回500错误。但是,当我添加上述配置代码段时,将显示错误页面,但HTTP状态代码更改为200。使用ASP.NET 4.0和4.5.0,解决方法是在404.aspx.cs中的重写渲染方法中手动设置Response.StatusCode。可能有更好的解决方案,但这似乎有效。那么,如果必须是静态文件,为什么要重定向到ASPX页面:-)它没有。文件必须存在于文件系统中。如果你想的话,我想你可以使用HTML文件。在我的例子中,ASPX页面在错误页面中呈现动态内容。