簡體   English   中英

HttpContext.Current.Session始終為空

[英]HttpContext.Current.Session Always Null

我知道這個話題已經出現了很多,但我找不到一個適用於我的問題的話題。

我有一個從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來解決SessionViewState等問題,這是對網絡性質的真正反對。 如您所知,在MVC中,所有操作和響應都應被視為無狀態請求,在處理請求之前和之后不應留下任何內容,並且假設GC將收集ViewBags,Session,Variables等中的所有數據。

因此,正如強烈推薦的那樣,處理此類事物的常用方法是使用通過純網絡提供的本機設施,例如cookie,html-forms,html-inputs,url參數等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM