[英]Routing for custom ASP.NET MVC 404 Error page
當有人鍵入不調用ASP.NET MVC中的有效操作或控制器的URL而不顯示通用的“未找到資源”ASP.NET錯誤時,我試圖創建自定義HTTP 404錯誤頁面。
我不想使用web.config來處理這個問題。
是否有任何類型的路由魔法可以捕獲任何無效的URL?
更新:我嘗試了給出的答案,但我仍然得到丑陋的“資源未找到”消息。
另一個更新:好的,顯然RC1中發生了一些變化。 我甚至試圖在HttpException
上專門捕獲404,它仍然只是給我“未找到資源”頁面。
我甚至使用過MvcContrib的資源功能,沒有 - 同樣的問題。 有任何想法嗎?
我試圖在生產服務器上啟用自定義錯誤3個小時,似乎我找到了最終解決方案如何在沒有任何路由的ASP.NET MVC中執行此操作。
要在ASP.NET MVC應用程序中啟用自定義錯誤,我們需要(IIS 7+):
在system.web
部分下的web配置中配置自定義頁面:
<customErrors mode="RemoteOnly" defaultRedirect="~/error"> <error statusCode="404" redirect="~/error/Error404" /> <error statusCode="500" redirect="~/error" /> </customErrors>
RemoteOnly
意味着在本地網絡上您將看到真正的錯誤(在開發過程中非常有用)。 我們還可以為任何錯誤代碼重寫錯誤頁面。
設置魔術響應參數和響應狀態代碼(在錯誤處理模塊或錯誤句柄屬性中)
HttpContext.Current.Response.StatusCode = 500; HttpContext.Current.Response.TrySkipIisCustomErrors = true;
在system.webServer
部分下的web配置中設置另一個魔術設置:
<httpErrors errorMode="Detailed" />
這是我發現的最后一件事,在此之后我可以在生產服務器上看到自定義錯誤。
我通過創建一個返回本文中視圖的ErrorController來使我的錯誤處理工作。 我還必須在global.asax中添加“Catch All”到路由。
如果它不在Web.config中,我無法看到它將如何到達任何這些錯誤頁面。? 我的Web.config必須指定:
customErrors mode="On" defaultRedirect="~/Error/Unknown"
然后我還補充說:
error statusCode="404" redirect="~/Error/NotFound"
NotFoundMVC - 只要在ASP.NET MVC3應用程序中找不到控制器,操作或路由,就會提供用戶友好的404頁面。 將呈現名為NotFound的視圖,而不是默認的ASP.NET錯誤頁面。
您可以使用以下命令通過nuget添加此插件:Install-Package NotFoundMvc
NotFoundMvc在Web應用程序啟動期間自動安裝。 它處理ASP.NET MVC通常拋出404 HttpException的所有不同方式。 這包括缺少控制器,動作和路線。
分步安裝指南:
1 - 右鍵單擊您的項目並選擇Manage Nuget Packages ...
2 - 搜索NotFoundMvc
並安裝它。
3 - 安裝完成后,將向項目中添加兩個文件。 如下面的屏幕截圖所示。
4 - 打開Views / Shared中新添加的NotFound.cshtml,並根據您的意願修改它。 現在運行應用程序並輸入一個不正確的URL,您將看到一個用戶友好的404頁面。
此外,用戶是否會Server Error in '/' Application. The resource cannot be found.
收到錯誤消息,如“ Server Error in '/' Application. The resource cannot be found.
Server Error in '/' Application. The resource cannot be found.
希望這可以幫助 :)
PS:感謝Andrew Davey制作了這么棒的插件。
在web.config中嘗試此操作以替換IIS錯誤頁面。 這是我猜的最佳解決方案,它也會發出正確的狀態代碼。
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" subStatusCode="-1" />
<remove statusCode="500" subStatusCode="-1" />
<error statusCode="404" path="Error404.html" responseMode="File" />
<error statusCode="500" path="Error.html" responseMode="File" />
</httpErrors>
</system.webServer>
此解決方案不需要web.config文件更改或catch-all路由。
首先,創建一個這樣的控制器;
public class ErrorController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Regular Error";
return View();
}
public ActionResult NotFound404()
{
ViewBag.Title = "Error 404 - File not Found";
return View("Index");
}
}
然后在“Views / Error / Index.cshtml”下創建視圖;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<p>We're sorry, page you're looking for is, sadly, not here.</p>
然后在Global asax文件中添加以下內容,如下所示:
protected void Application_Error(object sender, EventArgs e)
{
// Do whatever you want to do with the error
//Show the custom error page...
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Error";
if ((Context.Server.GetLastError() is HttpException) && ((Context.Server.GetLastError() as HttpException).GetHttpCode() != 404))
{
routeData.Values["action"] = "Index";
}
else
{
// Handle 404 error and response code
Response.StatusCode = 404;
routeData.Values["action"] = "NotFound404";
}
Response.TrySkipIisCustomErrors = true; // If you are using IIS7, have this line
IController errorsController = new ErrorController();
HttpContextWrapper wrapper = new HttpContextWrapper(Context);
var rc = new System.Web.Routing.RequestContext(wrapper, routeData);
errorsController.Execute(rc);
Response.End();
}
如果在執行此操作后仍然出現自定義IIS錯誤頁面,請確保在Web配置文件中注釋掉(或清空)以下部分:
<system.web>
<customErrors mode="Off" />
</system.web>
<system.webServer>
<httpErrors>
</httpErrors>
</system.webServer>
只需在路由表的末尾添加catch all route並顯示您想要的任何頁面。
如果您在MVC 4中工作,您可以觀看此解決方案,它對我有用。
將以下Application_Error方法添加到我的Global.asax
:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Server.ClearError();
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Index");
routeData.Values.Add("exception", exception);
if (exception.GetType() == typeof(HttpException))
{
routeData.Values.Add("statusCode", ((HttpException)exception).GetHttpCode());
}
else
{
routeData.Values.Add("statusCode", 500);
}
IController controller = new ErrorController();
controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
Response.End();
控制器本身非常簡單:
public class ErrorController : Controller
{
public ActionResult Index(int statusCode, Exception exception)
{
Response.StatusCode = statusCode;
return View();
}
}
在GitHub上查看Mvc4CustomErrorPage的完整源代碼。
我遇到了同樣的問題,您需要做的是,不必在Views文件夾的web.config文件中添加customErrors屬性,而是必須將它添加到項目根文件夾的web.config文件中
這是真正的答案,允許在一個地方完全自定義錯誤頁面。 無需修改web.config或創建單獨的代碼。
也適用於MVC 5。
將此代碼添加到控制器:
if (bad) {
Response.Clear();
Response.TrySkipIisCustomErrors = true;
Response.Write(product + I(" Toodet pole"));
Response.StatusCode = (int)HttpStatusCode.NotFound;
//Response.ContentType = "text/html; charset=utf-8";
Response.End();
return null;
}
基於http://www.eidias.com/blog/2014/7/2/mvc-custom-error-pages
我會談談一些具體的案例,
如果您在HomeController中使用'PageNotFound方法',如下所示
[Route("~/404")]
public ActionResult PageNotFound()
{
return MyView();
}
它不會起作用。 但是你必須清除下面的Route標簽,
//[Route("~/404")]
public ActionResult PageNotFound()
{
return MyView();
}
如果您在web.config中將其更改為方法名稱, 則可以正常工作。 但是不要忘記在web.config中執行如下代碼
<customErrors mode="On">
<error statusCode="404" redirect="~/PageNotFound" />
*// it is not "~/404" because it is not accepted url in Route Tag like [Route("404")]*
</customErrors>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.