2016-04-08 21 views
2

我有下面的代碼創建一個帶分佈:保持配置文件ID訪問通過應用

var bandProfile = _profileService.CreateBandProfile(model.BandProfile, file, UserId); 

    if (bandProfile != null) 
    { 
     userManager.AddToRole(UserId, "Band"); 
     //Store the bandprofile ID anywhere? 
     return RedirectToAction("Index", "Welcome"); 
    } 

不,我想存儲,使bandprofile ID通過應用程序訪問。保持它在用戶使用配置文件登錄時可訪問。

我該如何做到這一點?

例如,以獲取用戶標識,您可以通過應用程序這樣做:

UserId = System.Web.HttpContext.Current.User.Identity.GetUserId(); 

我想要做同樣的事情,但bandprofileId。

回答

0

對於這樣做的「正確性」存在一些爭議(下面鏈接),但您可以將變量存儲在HttpContext.Current.Application["BandProfile"]中。

if (bandProfile != null) 
{ 
    userManager.AddToRole(UserId, "Band"); 
    //Store the bandprofile ID anywhere? 
    HttpContext.Current.Application["BandProfile"] = bandProfile; 

    return RedirectToAction("Index", "Welcome"); 
} 

或者,您可以在某個類的某處使用static變量。

public static class BandProfile 
{ 
    public static whatever Profile; 
} 

if (bandProfile != null) 
{ 
    userManager.AddToRole(UserId, "Band"); 
    //Store the bandprofile ID anywhere? 
    BandProfile.Profile = bandProfile; 

    return RedirectToAction("Index", "Welcome"); 
} 

這裏是一個related question具有相同的問題交易,here是另一回事。

編輯:

然後,爲了訪問這些變量,你可以使用

var bandProfile = HttpContext.Current.Application["BandProfile"];

var bandProfile = BandProfile.Profile;

根據Microsoft

ASP.NET包含主要用於與經典ASP兼容的應用程序狀態,以便將現有應用程序遷移到ASP.NET更加容易。建議您將數據存儲在應用程序類的靜態成員中而不是應用程序對象中。

這就是說,你應該使用static變量方法。靜態變量可通過調用ClassName.Variable獲得,並且在應用程序運行期間存在。如果應用程序已關閉或者變量被另外更改,您將失去此信息。

爲了保存信息,有必要將此變量的內容寫入外部源(數據庫,文件等),並在應用程序啓動時讀取它。

+0

當我分配類變量的值,然後該值是永久存儲在該變量? – Bryan

+0

會話如何? – Bryan

+0

@Bryan我想爲你找到一個更具體的答案,但我的理解是變量設置爲用戶會話的持續時間。它不會成爲永遠存在的「永遠」的全球變量。 – levelonehuman

相關問題