gpt4 book ai didi

asp.net-mvc - 对于 ASP.NET 成员,我如何显示 403?

转载 作者:行者123 更新时间:2023-12-04 03:19:02 33 4
gpt4 key购买 nike

默认情况下,当用户无权访问 protected 页面时,ASP.NET 的成员身份提供程序会重定向到 loginUrl。

有没有办法在不重定向用户的情况下显示自定义 403 错误页面?

我想避免将用户发送到登录页面并在地址栏中包含 ReturnUrl 查询字符串。

如果有人有任何特定于 MVC 的建议,我正在使用 MVC(和 Authorize 属性)。

谢谢!

最佳答案

我最终只是创建了一个返回我的 Forbidden View 的自定义 Authorize 类。效果很好。

public class ForbiddenAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}

if (AuthorizeCore(filterContext.HttpContext))
{
// ** IMPORTANT **
// Since we're performing authorization at the action level, the authorization code runs
// after the output caching module. In the worst case this could allow an authorized user
// to cause the page to be cached, then an unauthorized user would later be served the
// cached page. We work around this by telling proxies not to cache the sensitive page,
// then we hook our custom authorization code into the caching mechanism so that we have
// the final say on whether a page should be served from the cache.

HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
cachePolicy.SetProxyMaxAge(new TimeSpan(0));
cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
}
else
{
// auth failed, display 403 page
filterContext.HttpContext.Response.StatusCode = 403;
ViewResult forbiddenView = new ViewResult();
forbiddenView.ViewName = "Forbidden";
filterContext.Result = forbiddenView;
}
}

private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus)
{
validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));
}
}

关于asp.net-mvc - 对于 ASP.NET 成员,我如何显示 403?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1847099/

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