Asp.net-Mvc
如何處理 MVC5 中配置和程式碼中的 404 錯誤?
我已經實現了下面連結中提到的異常處理
它工作正常。但我有要求處理
404 Error。我怎樣才能做到這一點?
如果我使用下面的程式碼,
<customErrors mode="On"> <error statusCode="404" redirect="/Home/Error"></error> </customErrors>發生任何
404錯誤時它都能正常工作。但是如果發生任何其他異常,那麼我的error.cshtml呼叫兩次並顯示相同的異常two times。
網路配置
關閉 system.web 中的自定義錯誤
<system.web> <customErrors mode="Off" /> </system.web>在 system.webServer 中配置 http 錯誤
<system.webServer> <httpErrors errorMode="Custom" existingResponse="Auto"> <clear /> <error statusCode="404" responseMode="ExecuteURL" path="/NotFound" /> <error statusCode="500" responseMode="ExecuteURL" path="/Error" /> </httpErrors> </system.webServer>創建簡單的錯誤控制器來處理這些請求ErrorContoller.cs
[AllowAnonymous] public class ErrorController : Controller { // GET: Error public ActionResult NotFound() { var statusCode = (int)System.Net.HttpStatusCode.NotFound; Response.StatusCode = statusCode; Response.TrySkipIisCustomErrors = true; HttpContext.Response.StatusCode = statusCode; HttpContext.Response.TrySkipIisCustomErrors = true; return View(); } public ActionResult Error() { Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; Response.TrySkipIisCustomErrors = true; return View(); } }配置路由RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes) { //...other routes routes.MapRoute( name: "404-NotFound", url: "NotFound", defaults: new { controller = "Error", action = "NotFound" } ); routes.MapRoute( name: "500-Error", url: "Error", defaults: new { controller = "Error", action = "Error" } ); //..other routes //I also put a catch all mapping as last route //Catch All InValid (NotFound) Routes routes.MapRoute( name: "NotFound", url: "{*url}", defaults: new { controller = "Error", action = "NotFound" } ); }最後確保您有控制器操作的視圖
Views/Shared/NotFound.cshtml Views/Shared/Error.cshtml如果您要處理任何其他錯誤,您可以按照該模式並根據需要添加。這將避免重定向並保持引發的原始 http 錯誤狀態。
如果您將為 customErrors 定義 defaultRedirect 屬性,那麼在您的情況下,error.cshtml 將只呈現一次:
<customErrors mode="On" defaultRedirect="/Home/Error"> <error statusCode="404" redirect="/Home/Error"/> </customErrors>