且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC - 如何显示在登录页未经授权的错误?

更新时间:2023-12-01 15:30:58

您可以查找?RETURNURL = 查询字符串值,也可以创建自己的授权滤波器放大器;在的TempData ​​ code>表示原因设置字段。

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>
}

(虽然我建议你比这些神奇的字符串一个更好的方法,但你明白了吧)