2012-09-17 32 views
1

在我的web.config文件下面的配置,ASP.NET 404重定向的查詢字符串缺少

<customErrors mode="On" redirectMode="ResponseRedirect" > 
    <error statusCode="404" redirect="/404" /> 
</customErrors> 
<httpErrors errorMode="Custom"> 
    <remove statusCode="404" subStatusCode="-1" /> 
    <error statusCode="404" prefixLanguageFilePath="" path="/404" responseMode="ExecuteURL" /> 
</httpErrors> 

404頁的作品不錯,但與一的.aspx重定向結尾的URL發生,查詢字符串爲網址被刪除。如果我將標記「customErrors」中的參數「redirectMode」更改爲「ResponseRewrite」,則它將停止爲.aspx網址工作,而我只是獲取默認的ASP.NET錯誤頁面。我怎樣才能解決這個問題?我需要404頁面上的查詢字符串才能將用戶重定向到正確的新網址。

/維克托

+0

以我的經驗,你不能只需使用配置即可完美解決問題。你需要一個對PageNotFoundExceptions起反應的HttpModule。在EPi社區中,有一些自定義的構建和可用的地方。 –

回答

0

好了,最後寫這個我自己的HTTP模塊,

public class FileNotFoundModule : IHttpModule 
{ 
    private static CustomErrorsSection _configurationSection = null; 
    private const string RedirectUrlFormat = "{0}?404;{1}"; 

    public void Dispose() 
    { 
    } 

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

    private void FileNotFound_Error(object sender, EventArgs e) 
    { 
     var context = HttpContext.Current; 
     if (context != null && context.Error != null) 
     { 
      var error = context.Error.GetBaseException() as HttpException; 
      if (error != null && error.GetHttpCode() == 404 && 
       (ConfigurationSecion.Mode == CustomErrorsMode.On || (!context.Request.IsLocal && ConfigurationSecion.Mode == CustomErrorsMode.RemoteOnly)) && 
       !string.IsNullOrEmpty(RedirectUrl) && !IsRedirectLoop) 
      { 
       context.ClearError(); 
       context.Server.TransferRequest(string.Format(FileNotFoundModule.RedirectUrlFormat, RedirectUrl, context.Request.Url)); 
      } 
     } 
    } 

    private bool IsRedirectLoop 
    { 
     get 
     { 
      var checkUrl = string.Format(FileNotFoundModule.RedirectUrlFormat,RedirectUrl,string.Empty); 
      return HttpContext.Current.Request.Url.ToString().Contains(checkUrl); 
     } 
    } 

    private CustomErrorsSection ConfigurationSecion 
    { 
     get 
     { 
      if (_configurationSection == null) 
      { 
       _configurationSection = (CustomErrorsSection)WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath).GetSection("system.web/customErrors"); 
      } 
      return _configurationSection; 
     } 
    } 

    private string RedirectUrl 
    { 
     get 
     { 
      foreach (CustomError error in ConfigurationSecion.Errors) 
      { 
       if (error.StatusCode == 404) 
       { 
        return error.Redirect; 
       } 
      } 
      return string.Empty; 
     } 
    } 
} 

爲我工作:)

/維克托