gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:14:55 25 4
gpt4 key购买 nike

我在 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]:从Web.config中删除所有“customErrors”和“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]:添加“Controllers / ErrorPageController.cs”
public class ErrorPageController : Controller
{
public ActionResult Error(int statusCode, Exception exception)
{
Response.StatusCode = statusCode;
ViewBag.StatusCode = statusCode + " Error";
return View();
}
}

[5]:在“ View /共享/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

关于asp.net-mvc - ASP.NET MVC 5自定义错误页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23565098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com