使用ASP.Net Web API 2,是否可以从AuthorizeAttribute过滤器
获取cookiepublic class SessionFilter : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
// I need to read cookie values here
// filterContext.??getCookies??
}
}
答案 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);
}