【问题标题】:HttpContext.Current.Session Always NullHttpContext.Current.Session 始终为空
【发布时间】: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);

    }

【问题讨论】:

标签: c# session asp.net-web-api


【解决方案1】:

MVC 移植到 asp.net 以解决诸如 SessionViewState 之类的问题,这些问题是对 Web 本质的真正反对。如您所知,在 MVC 中,所有操作和响应都应被视为无状态请求,在处理请求之前和之后不应留下任何内容,并且假设 GC 将收集 ViewBags、Session、Variables 等中的所有数据.

因此,强烈建议,处理此类事情的常用方法是使用通过纯 Web 提供的本地工具,例如 cookie、html-forms、html-inputs、url 参数等。

【讨论】:

  • 问题是关于 WebAPI 而不是 MVC。 WebAPI 不支持会话。要启用会话,请参阅 haim700 的评论。
  • WebAPI 只是 MVC 的一部分,它在 MVC 的运行时库上构建和运行。因此,MVC 和 WebAPI 自然没有区别
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-31
  • 2019-07-18
  • 2019-08-18
  • 2011-12-29
  • 2019-07-02
  • 2019-05-04
相关资源
最近更新 更多