微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – HttpContext.Current.Session始终为空

我知道这个话题已经出现了很多,但我找不到一个适用于我的问题的话题.

我有一个从ActionFilterattribute派生的GuestTokenValidationAttribute类,在那里我从头部接收一个令牌,并将其用作String令牌.然后我想将该标记添加到会话中,但无论我做什么,Session始终为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);

    }

解决方法

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

因此,正如强烈推荐的那样,处理此类事物的常用方法是使用通过纯网络提供的本机设施,例如cookie,html-forms,html-inputs,url参数等.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐