ASP.NET MVC - 如何在登录页面上显示未经授权的错误? [英] ASP.NET MVC - How to show unauthorized error on login page?
问题描述
在我的 ASP.NET MVC 应用程序中,我的大多数控制器都装饰有
In my ASP.NET MVC app, I have most controllers decorated with
[Authorize(Roles="SomeGroup")]
当用户无权访问某些内容时,他们将被发送到~/Login",这是我帐户控制器上的登录操作.
When a user is not authorized to access something, they are sent to "~/Login" which is the Login action on my Account controller.
如何确定用户由于未获得授权而到达登录页面,以便显示适当的错误?
How can I determine that a user has reached the login page because of not being authorized so that I can show an appropriate error?
推荐答案
您可以查找 ?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>
}
(虽然我推荐一种比这些魔法字符串更好的方法,但你懂的)
这篇关于ASP.NET MVC - 如何在登录页面上显示未经授权的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!