【发布时间】:2013-12-12 08:24:42
【问题描述】:
我知道这个话题已经出现了很多,但我还没有找到一个适合我的问题..
我有一个派生自 ActionFilterAttribute 的 GuestTokenValidationAttribute 类,在那里我从标头接收一个令牌,并将其用作字符串令牌。然后我想将该令牌添加到会话中,但无论我做什么,会话始终为空。
任何指导或帮助将不胜感激,
下面的代码示例:
public class GuestTokenValidationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
string token;
try
{
token = actionContext.Request.Headers.GetValues("Authorization-Token").First();
}
catch (Exception)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new StringContent("Unauthorized User")
};
return;
}
if(string.IsNullOrEmpty(token))
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new StringContent("Unauthorized User")
};
return;
}
try
{
var repository = DependencyResolver.Current.GetService<IRepository<Guest>>();
var guest = repository.GetAll().FirstOrDefault(x => x.Token == token);
if(guest == null)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new StringContent("Unauthorized User")
};
return;
}
}
catch (Exception)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new StringContent("Unauthorized User")
};
return;
}
HttpContext.Current.Session.Add("guesttoken" ,token);
base.OnActionExecuting(actionContext);
}
【问题讨论】:
-
您是否在 web.config 中启用了会话?
-
我有
-
这是在 API 控制器中吗?
-
@C Sharper,是的,它是一个 API 控制器
标签: c# session asp.net-web-api