當IIS 7上的ASP.NET請求是404時,我想要顯示自定義錯誤頁面。地址欄中的網址不應更改,因此不需要重定向。我怎樣才能做到這一點?如何在ASP.NET中顯示自定義404頁面而不重定向?
3
A
回答
2
在您的應用程序的OnError事件中,您可以測試狀態碼爲404的HttpExceptions,然後執行Server.Transfer到您的自定義404頁面而不是Response.Redirect。看看http://blog.dmbcllc.com/2009/03/02/aspnet-application_error-detecting-404s/
-1
您可以使用
Server.Transfer("404error.aspx")
1
我使用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>
5
作爲一般ASP.NET溶液,在web.config中的customErrors部分,添加redirectMode = 「ResponseRewrite」屬性。
<customErrors mode="On" redirectMode="ResponseRewrite">
<error statusCode="404" redirect="/404.aspx" />
</customErrors>
注意:這在內部使用Server.Transfer(),因此重定向必須是Web服務器上的實際文件。它不能是一個MVC路線。
相關問題
- 1. 顯示404自定義頁面而不重定向到它
- 2. 如何在ASP.NET-MVC中顯示自定義404頁面?
- 3. Symfony - 404總是重定向到登錄頁面而不是顯示自定義404頁面
- 4. 404錯誤被重定向到主頁而不是自定義404頁面
- 5. 404頁,而在笨頁面重定向
- 6. 的.htaccess不重定向而是404.php顯示頁面名稱
- 7. CMS和顯示自定義404頁面
- 8. 如何將用戶重定向到ASP.NET MVC中的自定義404頁面而不是拋出異常?
- 9. 404自定義重定向
- 10. 重定向到DjangoCMS中的自定義404 html頁面
- 11. 重定向到主目錄中的自定義404頁面
- 12. 如何將所有頁面擴展重定向到自定義404未在asp.net項目中找到頁面?
- 13. 如何從asp.net中的JS顯示頁面重定向到特定頁面
- 14. 重定向到新頁面而不顯示父頁面
- 15. ASP.NET MVC 4自定義404頁面
- 16. 自定義404頁面asp.net C對IIS6
- 17. 重定向到404頁面或顯示404消息?
- 18. Azure重定向到自定義404頁面
- 19. 重定向所有的404錯誤頁面自定義404頁CodeIgniter HMVC
- 20. .htaccess文件重定向到索引頁而不是自定義404頁
- 21. 在404錯誤自定義頁面中顯示失敗鏈接
- 22. Cloud9自定義404頁面
- 23. Nginx - 自定義404頁面
- 24. 如何使自定義404頁面成爲轉發,而不是Tomcat中的重定向
- 25. 重定向到新地址而不是顯示404錯誤頁面可以嗎?
- 26. 自定義頁面固定鏈接顯示404
- 27. 重定向頁面不顯示url值
- 28. .htaccess不會重定向到404頁面
- 29. method_for_query,重定向到自定義頁面
- 30. PHP重定向不顯示頁面內容重定向到
你有很多標籤 - 這是webforms還是MVC? – Macros 2009-09-02 13:47:03