簡體   English   中英

ASP.NET身份-擴展_LoginPartial

[英]ASP.NET Identity - extending the _LoginPartial

我發現這很難概括,因此問題名稱很差。 在使用身份的.net Web應用程序上,有一個登錄部分是自動生成的,它顯示用戶的“ username”屬性,如下所示:

@Html.ActionLink(User.Identity.GetUserName(), "Index", "Manage", routeValues: null, htmlAttributes: new {title = "Manage"})

對包含用戶數據的SQL數據庫進行概要分析后,我注意到對GetUserName()的此調用實際上並未對數據庫進行調用以檢索該名稱。 我正在尋找訪問'ApplicationUser'類的導航屬性,該屬性包含要顯示的縮略圖的URL。

但是,我希望可以實現此目標,而無需在每個頁面請求上都為URL調用數據庫。 例如,在此站點上,您的個人資料圖像將作為布局的一部分顯示在每個頁面上。

應用程序用戶類具有此屬性。

public class ApplicationUser : IdentityUser
{
    public UserProfile Profile { get; set; }
}

用戶個人資料類擁有此屬性。

public class UserProfile
{
    [Key, ForeignKey("User")]
    public string UserId { get; set; }
    public ApplicationUser User { get; set; }

    [Required]
    public string ThumbnailUrl { get; set; }

    ...
}

我怎樣才能做到這一點? 還是有更好的方法來實現這一目標。

您可以將它們添加為聲明。 進行身份驗證時,您應該從數據庫中獲取用戶並添加以后需要使用的所有屬性。

假設您在登錄用戶時使用的是CreateIdentity,則應該返回ClaimsIdentity對象。

var userIdentity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
userIdentity.AddClaim(new Claim("Thumbnail", user.ThumbnailUrl));

然后,您需要創建一個擴展類,比如說IdentityExtensions:

public static class IdentityExtensions{
    public static string Thumbnail(this IIdentity identity){
        try{
            return ((ClaimsIdentity) identity).FindFirst("Thumbnail").Value;
        }
         catch(Exception ex){
         // handle any exception the way you need
        }
    }
}

最后,在您的視圖上,您​​應該可以使用@ User.Identity.Thumbnail()

沒錯,它不會發出呼叫...原因是因為它會將數據保存在客戶端的Cookie中...如果不這樣做,則服務器如果必須不斷地往返運行,則會崩潰。為大型系統抓取這些瑣碎的數據...因此將其緩存。

在ASP.NET MVC中完成此操作的方式是通過使用IPrinciple接口...我將為您指明正確的方向,以了解更多信息... CodeProject:如何在MVC中實現自定義IPrincipal

最好的辦法是創建第二個表(或在當前表中添加一列),在注冊表單中添加文件上傳功能。 注冊成功后,使用EntityFramework將圖片添加到數據庫中。 創建一個頁面以按用戶ID返回圖片,以便可以將其包含在頁面中的某個位置。

你可以用這個主意

http://blogs.msdn.com/b/webdev/archive/2013/10/16/customizing-profile-information-in-asp-net-identity-in-vs-2013-templates.aspx

暫無
暫無

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

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