【问题标题】:Custom authorize attribute - can I store a value for later?自定义授权属性 - 我可以为以后存储一个值吗?
【发布时间】:2013-02-27 03:47:28
【问题描述】:

我有一个自定义的授权属性,它基本上只是验证一个 cookie 是随请求一起发送的,并且它有一个分配的值。

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext == null)
            throw new ArgumentNullException("filterContext");

        bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true)
                      || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true);

        if (skipAuthorization) return;

        var cookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];

        if (cookie != null)
        {
            var decCookie = FormsAuthentication.Decrypt(cookie.Value);

            if(decCookie != null)
            {
                if (!string.IsNullOrEmpty(decCookie.UserData))
                {
                    return;
                }
            }
        }

        HandleUnauthorizedRequest(filterContext);
    }

这可以满足我的需要,但是我是否可以将 decCookie.UserData 存储在可以在控制器操作中访问的某个位置?我做了一个扩展方法,无论如何都会从请求中在控制器中检索它,但它实际上只是属性已经完成的副本。

那么,有没有一种方法可以让我摆脱没有扩展方法,而只需将 UserData 存储在某个地方,以便以后直接从属性中使用到控制器中?

【问题讨论】:

    标签: asp.net-mvc c#-4.0 asp.net-mvc-4 custom-attributes


    【解决方案1】:

    使用自定义主体和身份,并在身份上存储您想要的任何数据。见MVC 3.0, Razor, Custom Principal and Identity。为了一个好的介绍。只需忽略有关使用Application_AuthenticateRequest 的部分,这就是您的Authorize 属性的用途。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-02
      • 2017-07-19
      • 2011-07-01
      • 1970-01-01
      • 2010-10-21
      • 2022-01-03
      相关资源
      最近更新 更多