更新时间:2023-12-01 15:39:10
您可以查找 ?ReturnUrl=
查询字符串值,或者您可以创建自己的授权过滤器 &在 TempData
中设置一个字段,表明原因.
You can look for the ?ReturnUrl=
querystring value, or you can create your own authorization filter & set a field in TempData
indicating the reason.
这是一个简单的自定义过滤器,可以解决问题:
Here is a simple custom filter that will do the trick:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
// NOTE: This is not thread safe, it is much better to store this
// value in HttpContext.Items. See Ben Cull's answer below for an example.
private bool _isAuthorized;
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
_isAuthorized = base.AuthorizeCore(httpContext);
return _isAuthorized;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if(!_isAuthorized)
{
filterContext.Controller.TempData.Add("RedirectReason", "Unauthorized");
}
}
}
然后在您看来,您可以执行以下操作:
Then in your view, you can do something like this:
@if(TempData["RedirectReason"] == "Unauthorized")
{
<b>You don't have permission to access that area</b>
}
(虽然我推荐一种比这些魔法字符串更好的方法,但你懂的)