2011-10-11 139 views
1

我在本地使用Asp.net 4 C#和IIS 7,并在生产服务器上使用IIS 7.5。在IIS 7.5和IIS 7上显示自定义错误页面

我需要显示自定义错误页面。目前,我在Global.asax中使用了一些逻辑来绕过IIS默认页面。 本地使用IIS 7我能够成功显示CustomPages,但在生产(IIS 7.5)服务器默认情况下IIS页面仍然存在。 我使用Response.TrySkipIisCustomErrors = true;,但在生产服务器上不起作用。

你能指出我解决这个问题的方法吗?

我的代码在Global.Asax

Application_Error 

Response.TrySkipIisCustomErrors = true; 
       if (ex is HttpException) 
       { 
        if (((HttpException)(ex)).GetHttpCode() == 404) 
        { 

         Server.Transfer("~/ErrorPages/404.aspx"); 
        } 
       } 
       // Code that runs when an unhandled error occurs. 
       Server.Transfer("~/ErrorPages/Error.aspx"); 
+0

感谢您的编辑 – GibboK

+0

只是出于好奇,为什么你不只是让你的web.config处理自定义错误?必要时登录application_error并让配置处理下一个。更容易打开/关闭,配置等。 –

+0

亚当我做服务器转移得到404。显示时出现的Asp.net自定义错误显示302默认情况下重定向 – GibboK

回答

2

我做了这是一个模块,而不是在Global.asax并迷上它为标准自定义错误的东西的方式。试试这个:

public class PageNotFoundModule : IHttpModule 
{ 
    public void Dispose() {} 

    public void Init(HttpApplication context) 
    { 
     context.Error += new EventHandler(context_Error); 
    } 

    private void context_Error(object sender, EventArgs e) 
    { 
     var context = HttpContext.Current; 

     // Only handle 404 errors 
     var error = context.Server.GetLastError() as HttpException; 
     if (error.GetHttpCode() == 404) 
     { 
      //We can still use the web.config custom errors information to decide whether to redirect 
      var config = (CustomErrorsSection)WebConfigurationManager.GetSection("system.web/customErrors"); 

      if (config.Mode == CustomErrorsMode.On || (config.Mode == CustomErrorsMode.RemoteOnly && context.Request.Url.Host != "localhost")) 
      { 
       //Set the response status code 
       context.Response.StatusCode = 404; 

       //Tell IIS 7 not to hijack the response (see http://www.west-wind.com/weblog/posts/745738.aspx) 
       context.Response.TrySkipIisCustomErrors = true; 

       //Clear the error otherwise it'll get handled as usual 
       context.Server.ClearError(); 

       //Transfer (not redirect) to the 404 error page from the web.config 
       if (config.Errors["404"] != null) 
       { 
        HttpContext.Current.Server.Transfer(config.Errors["404"].Redirect); 
       } 
       else 
       { 
        HttpContext.Current.Server.Transfer(config.DefaultRedirect); 
       } 
      } 
     } 
    } 
} 
+0

我在尝试,你可以发布你的Web.Config的例子吗?谢谢 – GibboK

+0