我知道这个话题经常出现,但是我没有找到适合我的问题的解决方法。
我有一个GuestTokenValidationAttribute类,它派生自ActionFilterAttribute,在那里我从头部接收一个令牌,并将其用作字符串令牌。然后,我想将该令牌添加到会话中,但无论我做什么,会话始终为null。
请大家提供任何指导或帮助将不胜感激,
以下是示例代码:
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);
}