HttpContext.Current.Session始终为null

4

我知道这个话题经常出现,但是我没有找到适合我的问题的解决方法。

我有一个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);

    }

6
你在web.config中启用了会话吗? - RononDex
我有没有 <sessionState mode="InProc" customProvider="DefaultSessionProvider">。 - Jacob O'Brien
这是在API控制器中吗? - CodeTherapist
@C Sharper,是的,它是一个API控制器。 - Jacob O'Brien
1
请看这里:https://dev59.com/92gu5IYBdhLWcg3wOUq- - haim770
1个回答

1

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

因此,高度推荐的处理方式是使用通过纯Web提供的本地设施,例如cookies、html-forms、html-inputs、url参数等。


问题是关于WebAPI而不是MVC。WebAPI不支持会话。要启用会话,请参见haim700的评论。 - LostInComputer
WebAPI只是MVC的一部分,它们都建立和运行在MVC的运行时库上。因此,MVC和WebAPI自然没有区别。 - Ali Dehghan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接