ASP.NET MVC - 如何显示在登录页未经授权的错误? [英] ASP.NET MVC - How to show unauthorized error on login page?

查看:420
本文介绍了ASP.NET MVC - 如何显示在登录页未经授权的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP.NET MVC应用程序,我有大多数控制器饰以

In my ASP.NET MVC app, I have most controllers decorated with

[Authorize(Roles="SomeGroup")]

当用户没有被授权访问的东西,它们被发送到〜/登录,这是对我的账户控制器的登录操作。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆