2016-11-14 38 views
1

我有一個HTTPGET方法下面的代碼在一個控制器ASP.NET是有可能使用會話和HttpContext.Application在圖書館

​​

我想收起庫中的代碼[DLL ]因此,在圖書館我有

// Inside DLL Library 
// namespace MyNS, class MyCl 

public void InitVars() 
{ 
    Session["var1"] = "someval1"; 
    HttpContext.Application["var2"] = "someval2"; 
} 

和呼叫這個從我的控制器Get方法

//在控制器類HTTPGET

InitVars(); 

如何訪問會話&應用對象庫中

我得到的錯誤

名會話不會在目前情況下

名稱存在的HttpContext不不存在於當前的情況下

這怎麼可能是d一?

回答

3

你只需要在Visual Studio中打開代碼庫的.csproj和set a referenceSystem.Web.dll和相同的代碼將在工作DLL。

您可以使用下面的代碼獲得了當前的HttpContext參考:

var context = System.Web.HttpContext.Current; 

之後,你可以簡單地調用

context.Session["var1"] = "someval1"; 
context.Application["var2"] = "someval2"; 
0

這工作

void InitLogin(System.Web.HttpSessionStateBase Session, 
      System.Web.HttpApplicationStateBase Application) 
{ 
    Session["var1"] = "someval1"; 
    Application["var2"] = "someval2"; 
} 

,並把它作爲

InitVars(Session, Application); 
+0

你也可以通過'System.Web.HttpContext.Current.Session'和'System.Web.HttpContext.Current.Application'靜態訪問它們。 – mason

0

如何訪問會話&應用對象庫中

不要直接做,你會結合你的代碼。我建議使用Adapter Pattern。像這樣的(未經測試)的東西:

類庫:

public interface IStorage 
{ 
    T GetSession<T>(string key); 
    void SetSession<T>(string key, T value); 
    T GetGlobal<T>(string key); 
    void SetGlobal<T>(string key, T value); 
} 

public void InitVars(IStorage storage) 
{ 
    storage.SetSession("var1", "someval1"); 
    storage.SetGlobal("var2", "somval2"); 
} 

Web應用程序:

public class WebStorage : IStorage 
{ 
    public T GetSession<T>(string key) 
    { 
    var result = Session[key] as T; 
    return result; 
    } 
    public void SetSession<T>(string key, T value) 
    { 
    Session[key] = value; 
    } 
    // etc with Global 
} 


InitVars(new WebStorage); 

現在你有任何的網絡課程沒有依賴關係。如果你決定使用asp.net核心(沒有HttpContext.Current等等),你可以很容易地修改你的WebStorage類而不必改變你的類庫。