2014-12-07 42 views
1

我開始使用WebForms .NET 4.51應用程序。然後我將WebAPI添加到同一個應用程序中。在在session_start()我創建了一個變量實例,我存儲在會話中,如下所示:.NET WebForms應用程序會話信息不適用於MVC

public class Global : HttpApplication 
{ 
     protected void Session_Start(object aSender, EventArgs aEventArgs) 
     {    
      //Create an object to hold all the settings for the user in the session. This is only loaded once we 
      //have a user successfully logged in 
      HttpContext.Current.Session[SYSTEM_SETTINGS_SESSION_KEY] = new SystemSettings(); 
     } 
} 

,我有一個簡單的屬性訪問如下:

public class Global : HttpApplication 
{ 
    public static SystemSettings SystemSettings 
    { 
      get 
      { 
       if (HttpContext.Current == null) 
        return null; 

       return HttpContext.Current.Session[SYSTEM_SETTINGS_SESSION_KEY] as SystemSettings; 
      } 
     } 
} 

上述一切運作良好,當我訪問來自代碼屬性除了當我試圖從一個的WebAPI控制器內執行此操作如下通過屬性從上方即Global.SystemSettings

public class EmailActivitiesController : ApiController 
{ 
    emailBody = EmailToClientsTemplateBuilderHelper.TemplateContentBuild(emailBody, Global.SystemSettings); 
} 

當我檢查HttpContext.Current.SessionNULL

那麼爲什麼當從WebAPI控制器訪問會話集合爲空?

我需要在WebAPI控制器中存儲與用戶會話相關的信息,所以我需要現在以不同的方式存儲事物嗎?

UPDATE

接受的解決方案還曾經的WebAPI 1這是什麼應用程序使用。

回答

0

這是因爲WebApi沒有默認啓用SessionWebApi正在試圖鼓勵您向移動,無狀態HTTPRESTful API

我強烈建議您在沒有會話的情況下重新修改您的設計。

與此說,你可以在2的WebAPI加入這個使會話的Global.asax

protected void Application_PostAuthorizeRequest() 
{ 
    System.Web.HttpContext.Current.SetSessionStateBehavior(
     System.Web.SessionState.SessionStateBehavior.Required); 
} 
+2

我聽到你關於無會話,不幸的是這個程序有幾年它背後已經和利用會議相當重。 – TheEdge 2014-12-08 22:31:17

相關問題