从AuthorizeAttribute Filter获取cookie

时间:2014-06-16 16:31:36

标签: asp.net asp.net-mvc asp.net-web-api

使用ASP.Net Web API 2,是否可以从AuthorizeAttribute过滤器

获取cookie
public class SessionFilter : AuthorizeAttribute
{
     public override void OnAuthorization(AuthorizationContext filterContext) 
     {
          // I need to read cookie values here
          // filterContext.??getCookies??

     }

}

2 个答案:

答案 0 :(得分:7)

从AuthorizationContext获取cookie:

filterContext.HttpContext.Request.Cookies

方法示例:

public class SessionFilter : AuthorizeAttribute

{
     public override void OnAuthorization(AuthorizationContext filterContext) 
     {
          // I need to read cookie values here
          HttpCookie cookie = filterContext.HttpContext.Request.Cookies.Get("Cookie Name");    
     }

}

答案 1 :(得分:0)

分享我的功能以在AuthorizationContext中实现i18n

  public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
    {
        string culureName = "en-US";
        HttpCookie cultureCookie = filterContext.RequestContext.HttpContext.Request.Cookies["lang"];
        if (cultureCookie != null
              && !string.IsNullOrWhiteSpace(cultureCookie.Value)
              && cultureCookie.Value != "null")
        {
            if (cultureCookie.Value == "en")
            {
                culureName = "en-US";
            }
            else if (cultureCookie.Value == "cn")
            {
                culureName = "zh-CN";
            }
        }
        Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(culureName);
        Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
        base.OnAuthorization(filterContext);
    }