簡體   English   中英

我們可以擴展HttpContext.User.Identity在asp.net中存儲更多數據嗎?

[英]Can we extend HttpContext.User.Identity to store more data in asp.net?

我使用asp.net身份。 我創建了實現用戶身份的默認asp.net mvc應用程序。 該應用程序使用HttpContext.User.Identity來檢索用戶ID和用戶名:

string ID = HttpContext.User.Identity.GetUserId();
string Name = HttpContext.User.Identity.Name;

我可以自定義AspNetUsers表。 我在這個表中添加了一些屬性,但希望能夠從HttpContext.User中檢索這些屬性。 那可能嗎 ? 如果有可能,我該怎么辦?

您可以將聲明用於此目的。 默認的MVC應用程序在類上有一個方法,表示系統中名為GenerateUserIdentityAsync用戶。 在該方法中有一條評論說// Add custom user claims here 您可以在此處添加有關用戶的其他信息。

例如,假設您要添加喜歡的顏色。 你可以這樣做

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
    // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
    var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
    // Add custom user claims here
    userIdentity.AddClaim(new Claim("favColour", "red"));
    return userIdentity;
}

在您的控制器中,您可以通過將User.Identity強制轉換為ClaimsIdentity (位於System.Security.Claims )來訪問聲明數據,如下所示

public ActionResult Index()
{
    var FavouriteColour = "";
    var ClaimsIdentity = User.Identity as ClaimsIdentity;
    if (ClaimsIdentity != null)
    {
        var Claim = ClaimsIdentity.FindFirst("favColour");
        if (Claim != null && !String.IsNullOrEmpty(Claim.Value))
        {
            FavouriteColour = Claim.Value;
        }
    }

    // TODO: Do something with the value and pass to the view model...

    return View();
}

聲明是好的,因為它們存儲在cookie中,因此一旦您在服務器上加載並填充它們一次,您就不需要再次訪問數據庫來獲取信息。

暫無
暫無

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

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