gpt4 book ai didi

asp.net-mvc - ASP.NET MVC 抛出并处理来自 Controller 的错误

转载 作者:行者123 更新时间:2023-12-01 05:42:19 24 4
gpt4 key购买 nike

在我的 Controller 中,让我们说编辑用户。在我的 Controller 中,我检查用户是否有权编辑,然后我想抛出某种身份验证或禁止错误,这会导致错误页面。

有没有办法做到这一点,而不是仅仅为错误创建 Controller 和操作?这样做的正确方法是什么?

最佳答案

这是您可以使用的自定义授权属性的示例:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
// if the user is not authenticated render the AccessDenied view
filterContext.Result = new ViewResult { ViewName = "AccessDenied" };
}
}
}

然后用这个属性装饰你的 Controller Action :
[CustomAuthorizeAttribute]
public ActionResult SomeAction()
{
...
}

您应该注意这种方法的一个警告。如果用户未获得授权,服务器会发送 200 状态码,这对 SEO 不太友好。最好发送 401 状态码。问题是,如果您使用表单例份验证,则会有一个自定义模块附加到 ASP.NET 执行管道中,并且每当服务器发送 401 状态代码时,它都会被拦截并自动重定向到登录页面。此功能是设计使然,不是 ASP.NET MVC 中的错误。一直都是这样。

事实上,有一种方法可以解决这种不愉快的情况:

您可以像这样修改自定义授权过滤器:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
// if the user is not authenticated render the AccessDenied view
filterContext.HttpContext.Items["unauthorized"] = true;
}
}
}

在 Global.asax 中:
protected void Application_EndRequest()
{
if (Context.Items.Contains("unauthorized"))
{
Context.Response.Clear();
Context.Response.StatusCode = 401;
Context.Server.Transfer("~/401.htm");
}
}

现在好多了。您会获得带有自定义错误页面的 401 状态代码。好的。

关于asp.net-mvc - ASP.NET MVC 抛出并处理来自 Controller 的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4682922/

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