Reputation: 723
I know this topic has come up a lot, but I haven't found one that works for my problem..
I have a GuestTokenValidationAttribute Class that derives from ActionFilterAttribute, in there I receive a token from the header and I use it as a String token. Then I want to add that token to a session, but no matter what I do the Session is always null.
Please guys any guidance or help will be much appreciated,
Code Example below:
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);
}
Upvotes: 4
Views: 6844
Reputation: 462
MVC ported to asp.net to solve problems such as Session and ViewState which were a true opposition against the nature of the web. As you know, in MVC, all actions and responses should be considered as stateless requests which nothing should be left before and after processing the request and assumed GC will collect all data in ViewBags, Session, Variables, etc.
So, as highly recommended, the common way of handling such thing is using native facilities delivered through pure web such as cookies, html-forms, html-inputs, url parameters, etc.
Upvotes: 1