2013-12-12 72 views
4

我知道这个话题已经涨了不少,但我还没有找到一个我的问题工程..HttpContext.Current.Session总是空

我有一个GuestTokenValidationAttribute类,从ActionFilterAttribute派生,在那里我从头部收到一个令牌,并将其用作String令牌。然后我想将该令牌添加到会话中,但无论我做什么,Session都始终为空。

请你们任何指导或帮助将非常感激,

代码下面的示例:

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); 

    } 
+6

您是否在web.config中启用了会话? – RononDex

+0

我是否有

+0

这是API控制器吗? –

回答

1

MVC移植到asp.net解决诸如会议的ViewState这是问题对网络性质的真正反对。如您所知,在MVC中,所有操作和响应都应视为无状态请求,在处理请求之前和之后都不应该留下任何内容,并假定将收集ViewBag,会话,变量等中的所有数据。

因此,强烈建议,处理此类事件的常见方式是使用通过纯Web提供的本地设施,例如cookie,html表单,html输入,url参数等。

+0

问题是关于WebAPI而不是MVC。 WebAPI不支持会话。要启用会话,请参阅haim700的评论。 – LostInComputer

+0

WebAPI只是MVC的一部分,它是在MVC的运行时库上构建和运行的。因此,MVC和WebAPI自然不会有所不同 –