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

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

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

<system.web>
    <customErrors mode="On" defaultRedirect="/Error/Error">
      <error statusCode="403" redirect="/Error/NoPermissions"/>
    </customErrors>
</system.web>

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

解决方法

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

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

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }
}

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

public void Application_Error(Object sender,EventArgs e)
{
    Exception exception = Server.GetLastError();
    Server.ClearError();

    var routeData = new RouteData();
    routeData.Values.Add("controller","ErrorPage");
    routeData.Values.Add("action","Error");
    routeData.Values.Add("exception",exception);

    if (exception.GetType() == typeof(HttpException))
    {
        routeData.Values.Add("statusCode",((HttpException)exception).GetHttpCode());
    }
    else
    {
        routeData.Values.Add("statusCode",500);
    }

    Response.TrySkipIisCustomErrors = true;
    IController controller = new ErrorPageController();
    controller.Execute(new RequestContext(new HttpContextWrapper(Context),routeData));
    Response.End();
}

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

public class ErrorPageController : Controller
{
    public ActionResult Error(int statusCode,Exception exception)
    {
         Response.StatusCode = statusCode;
         ViewBag.StatusCode = statusCode + " Error";
         return View();
    }
}

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

@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = (!String.IsNullOrEmpty(ViewBag.StatusCode)) ? ViewBag.StatusCode : "500 Error";
}

<h1 class="error">@(!String.IsNullOrEmpty(ViewBag.StatusCode) ? ViewBag.StatusCode : "500 Error"):</h1>

//@Model.ActionName
//@Model.ControllerName
//@Model.Exception.Message
//@Model.Exception.StackTrace

:D

原文链接:https://www.f2er.com/aspnet/253549.html

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