2017-12-18 292 views
1

我正在用AngularJS開發ASPN.NET WEB API 1(使用.NET Framework 4.0)應用程序,並且我正在使用會話來驗證用戶(我知道它應該無國籍,但爲了遺留目的,我正在使用會話)。在我的應用程序中,每次向我的WEB API發出請求時,都會創建一個新的會話,即使我爲會話設置了值。在web api的每個請求中都創建了一個新會話

的會話是允許在我的器件的應用,通過這個代碼在Global.asax中:

protected void Application_BeginRequest(object sender, EventArgs e) 
     { 

      string origins = ConfigurationManager.AppSettings["cors-origins"]; 
      bool hasSlash = origins.Substring(origins.Length - 1, 1) == "/"; 
      if (hasSlash) 
       origins = origins.Substring(0, origins.Length - 1); 

      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", origins); 
      if (HttpContext.Current.Request.HttpMethod == "OPTIONS") 
      { 
       HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", 
          "GET, POST, PUT, DELETE"); 
       HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", 
          "Content-Type, Accept"); 
       HttpContext.Current.Response.End(); 
      } 
     } 

     protected void Application_PostAuthorizeRequest() 
     { 
      if (IsWebApiRequest()) 
      { 
       HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required); 
      } 
     } 

然後我設定值,我會在我的控制器:

public HttpResponseMessage Post(LoginViewModel model) 
    { 
    // SOME BUSINESS LOGIC HERE... 

     FormsAuthentication.SetAuthCookie(model.User, false); 
     HttpContext.Current.Session["usuario"] = model.User; 
     return Request.CreateResponse(HttpStatusCode.Accepted, "User successfylly logged in!"); 
    } 

但是,當我做的另一個請求我的應用程序訪問控制器中的另一種方法,它會拋出一個錯誤,因爲會話爲空,就像在此方法中一樣:

public HttpResponseMessage Get() 
    { 
     var userName = HttpContext.Current.Session["usuario"]; 

     return Request.CreateResponse(HttpStatusCode.Accepted, userName); 
    } 

在我的web.config,會話配置是這樣的:

<sessionState mode="InProc" customProvider="DefaultSessionProvider" > 
     <providers> 
     <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" /> 
     </providers> 
    </sessionState> 

PS:它無法在Chrome工作,但在IE上它的工作原理,並直接在郵遞員它也可以做的請求。

+0

當你建立一個API,每個請求都是獨立的,無論在什麼方面,以任何過去或未來的請求沒有任何關係。你不是在這裏建立一個Web應用程序。如果您想知道誰在發送請求,請查看身份驗證機制,例如oauth或您認爲合適的任何其他身份驗證機制。只要不要像一個網絡應用程序對待一個API,這裏沒有傳統的藉口。 –

回答

1

它缺少這一行我Application_BeginRequest

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true"); 

並在AngularJS每個請求我應該通過withCredentials參數爲真。爲了實現這一目標,我把這個線在我的配置文件在AngularJS:

$httpProvider.defaults.withCredentials = true; 
相關問題