得到授权许可的属性? [英] Get permission from Authorize Attribute?

查看:215
本文介绍了得到授权许可的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现我自己的授权属性,而且我注意到它查询到检查权限当我使用 [授权]

I've implemented my own Authorize attribute, and I notice that it queries to check permissions when I use [Authorize].

有没有什么方法可以让我得到了许可,并用它在适用的授权属性,而无需重写和重新查询code。在电流控制器控制器?

Is there any way I can get that permission and use it in the current controller that applies the Authorize attribute without having to rewrite and requery the code in the controller?

推荐答案

是的,你可以。如果您实现您的授权属性为ActionFilterAttribute可以使用的ViewData集合来存储信息是这样的:

Yes, you can. If you implemented your Authorize attribute as an ActionFilterAttribute you can use the ViewData collection to store information like this :

    public class RequireRegistrationActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpRequestBase request = filterContext.HttpContext.Request;
        HttpResponseBase response = filterContext.HttpContext.Response;

        if (request != null && 
            response != null)
        {
            bool isAuthenticated = request.IsAuthenticated;
            filterContext.Controller.ViewData["IsAuthenticated"] = isAuthenticated;

            if (!isAuthenticated)
            {
                string url = String.Format(
                   "/?ReturnUrl={0}", 
                   HttpUtility.UrlEncode(request.Url.ToString()));
                response.Redirect(url);
            }
        }
    }
}

在anoteated控制器的acrion您可以访问该字段:

In the anoteated controller's acrion you can access the field with:

bool isAuthenticated = (bool)(ViewData["IsAuthenticated"] ?? false);

这篇关于得到授权许可的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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