C# MVC模式 404 500頁面設置方法


<customErrors mode="On" defaultRedirect="Controllers/Action">
<error statusCode="403" redirect="Controllers/Action" /> <error statusCode="404" redirect="Controllers/Action" /> </customErrors> 這里不是對應你想轉到的頁面而是你所想跳轉的某個Controllers 中的某個Action

 

方法二:

復制代碼
protected void Application_EndRequest() { var statusCode = Context.Response.StatusCode; var routingData = Context.Request.RequestContext.RouteData; if (statusCode == 404 || statusCode == 500) { Response.Clear(); var area = DataHelper.ConvertTo(routingData.DataTokens["area"], string.Empty); if (area == "Admin") { Response.RedirectToRoute("Admin_Default", new { controller = "BackError", action = "NotFound", IsReload = 1 }); } else { Response.RedirectToRoute("Default", new { controller = "Error", action = "NotFound", id = UrlParameter.Optional }); } } }
復制代碼

 

 

方法三:

Global.aspx.cs
public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new CustomHandlerErrorAttribute()); } 

 

CustomHandlerErrorAttribute.cs

復制代碼
public class CustomHandlerErrorAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { if (filterContext.ExceptionHandled) { return; } filterContext.Controller.ViewData.Model = filterContext.Exception; filterContext.Result = new ViewResult { ViewName = "Error", ViewData = filterContext.Controller.ViewData }; filterContext.ExceptionHandled = true; } } 
復制代碼

 

web.config <system.web>

<customErrors mode="On"> <error redirect="/home/error" statusCode="404" /> </customErrors> 

 

web.config  <system.webServer>

<httpErrors errorMode="Custom" existingResponse="PassThrough"> </httpErrors> 

 

Error.cshtml

復制代碼
<div class="box"> @{ var exception = ViewData.Model; var statusCode = exception == null ? 404 : 500; Response.StatusCode = statusCode; if (statusCode == 404) { <h3>404 Page not found!</h3> <p>沒有找到該網頁!</p> } else if (statusCode == 500) { <h3>500 程序異常</h3> <p>@exception.Message</p> } } <p style="font-size: 12px; color: Gray">請使用瀏覽器的后退功能已保證您填寫的數據沒有丟失!</p> </div> 
復制代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM