Get permission from Authorize Attribute?

安稳与你 提交于 2019-12-19 09:19:38

问题


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

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?


回答1:


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

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

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


来源:https://stackoverflow.com/questions/1938835/get-permission-from-authorize-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!