asp.net-mvc – ASP.NET MVC 5自定义错误页面

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – ASP.NET MVC 5自定义错误页面前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在ASP.NET MVC 5应用程序中使用自定义授权属性,如下所示:
  1. public class CustomAuthorizeAttribute : AuthorizeAttribute
  2. {
  3. protected override void HandleUnauthorizedRequest(AuthorizationContext context)
  4. {
  5. if (context.HttpContext.Request.IsAuthenticated)
  6. {
  7. context.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
  8. }
  9. else
  10. {
  11. base.HandleUnauthorizedRequest(context);
  12. }
  13. }
  14. }

在我的web.config的system.web部分我提到了错误路径,如:

  1. <system.web>
  2. <customErrors mode="On" defaultRedirect="/Error/Error">
  3. <error statusCode="403" redirect="/Error/NoPermissions"/>
  4. </customErrors>
  5. </system.web>

但是我从未重定向到/ Error / NoPermissions的自定义错误页面。相反,浏览器会显示“HTTP错误403.0 – 禁止”的常规错误页面

解决方法

[1]:删除所有’customErrors’&来自Web.config的’httpErrors’

[2]:检查’App_Start / FilterConfig.cs’如下所示:

  1. public class FilterConfig
  2. {
  3. public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  4. {
  5. filters.Add(new HandleErrorAttribute());
  6. }
  7. }

[3]:在“Global.asax”中添加方法

  1. public void Application_Error(Object sender,EventArgs e)
  2. {
  3. Exception exception = Server.GetLastError();
  4. Server.ClearError();
  5.  
  6. var routeData = new RouteData();
  7. routeData.Values.Add("controller","ErrorPage");
  8. routeData.Values.Add("action","Error");
  9. routeData.Values.Add("exception",exception);
  10.  
  11. if (exception.GetType() == typeof(HttpException))
  12. {
  13. routeData.Values.Add("statusCode",((HttpException)exception).GetHttpCode());
  14. }
  15. else
  16. {
  17. routeData.Values.Add("statusCode",500);
  18. }
  19.  
  20. Response.TrySkipIisCustomErrors = true;
  21. IController controller = new ErrorPageController();
  22. controller.Execute(new RequestContext(new HttpContextWrapper(Context),routeData));
  23. Response.End();
  24. }

[4]:添加“控制器/ ErrorPageController.cs”

  1. public class ErrorPageController : Controller
  2. {
  3. public ActionResult Error(int statusCode,Exception exception)
  4. {
  5. Response.StatusCode = statusCode;
  6. ViewBag.StatusCode = statusCode + " Error";
  7. return View();
  8. }
  9. }

[5]:在“Views / Shared / Error.cshtml”

  1. @model System.Web.Mvc.HandleErrorInfo
  2. @{
  3. ViewBag.Title = (!String.IsNullOrEmpty(ViewBag.StatusCode)) ? ViewBag.StatusCode : "500 Error";
  4. }
  5.  
  6. <h1 class="error">@(!String.IsNullOrEmpty(ViewBag.StatusCode) ? ViewBag.StatusCode : "500 Error"):</h1>
  7.  
  8. //@Model.ActionName
  9. //@Model.ControllerName
  10. //@Model.Exception.Message
  11. //@Model.Exception.StackTrace

:D

猜你在找的asp.Net相关文章