English 中文(简体)
如何在协会中展示404页的习俗。 该网络没有改头吗?
原标题:How to show a custom 404 page in ASP.NET without redirect?
  • 时间:2009-09-02 13:41:41
  •  标签:

如申请书为404份。 互联网站 7 i 想要展示一个习俗错误页。 The URL in the Address bar should not change, so no redirect. 如何做到这一点?

问题回答

作为一个一般的协会。 NET办法,在网上的海关校外科,加上“ResponseRewrite”属性。

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

注:这一内部使用服务器。 因此,转头必须是网络服务器上的实际档案。 这条路可以是MVC路线。

我使用一个http://www.un.org。 它处理其他类型的错误,而不仅仅是404个错误,并允许你继续使用海关错误网络。 栏目显示哪页。

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

• 上网。 与其他模块的组合方式相同。

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

你们可以使用

Server.Transfer("404error.aspx")




相关问题
热门标签