Trong số ASP.Net MVC 5
, các ApplicationUser
có thể được mở rộng để có thuộc tính tùy chỉnh. Tôi đã mở rộng nó như vậy mà nó bây giờ có một tài sản mới được gọi là DisplayName
:Làm thế nào để có được giá trị thuộc tính tùy chỉnh của ApplicationUser trong ASP.Net MVC 5 View?
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser {
public string ConfirmationToken { get; set; }
public string DisplayName { get; set; } //here it is!
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
return userIdentity;
}
}
Tôi cũng đã cập nhật các bảng cơ sở dữ liệu sử dụng Update-Database
lệnh trong Package-Manager Console
trong Visual Studio
để đảm bảo tính nhất quán giữa ApplicationUser
class
và AspNetUsers
bảng. Tôi đã xác nhận rằng cột mới có tên DisplayName
hiện đã tồn tại trong bảng AspNetUsers
.
Bây giờ, tôi muốn sử dụng mà DisplayName
thay vì mặc định UserName
cho văn bản trong bản gốc _LoginPartial.cshtml
View
. Nhưng như bạn có thể thấy:
<ul class="nav navbar-nav navbar-right">
<li>
@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
Bản gốc _LoginPartialView.cshtml
đang sử dụng User.Identity.GetUserName()
để có được những UserName
của ApplicationUser
. User.Identity
có GetUserId
và cũng Name
, AuthenticationType
, v.v ... Nhưng làm cách nào để nhận được DisplayName
để hiển thị?
Điều này có vẻ đầy hứa hẹn ... bạn thường đặt phương thức 'IdentiyExtensions' ở đâu? Trong 'IdentityModels.cs'? Hay bạn sẽ tạo một tập tin mới với quy ước tên nào đó cho nó? – Ian
Tôi sẽ tạo một tệp mới có tên "IdentityExtensions.cs", có thể bên trong một thư mục có tên "Người giúp đỡ" – tmg
Cảm ơn câu trả lời của bạn! Nó hoạt động! Tôi thực hiện một chút sửa đổi mặc dù ... thay vì trả về 'return claim.FindFirst (" DisplayName ")', tôi trả về 'return claim.FindFirst (" DisplayName "). ToString(). Substring ((" DisplayName: "). Chiều dài); '- điều này là bởi vì' claim.FindFirst ("DisplayName") 'là kiểu' Claim' nhưng 'return' cần phải là một' chuỗi'. Ngoài ra, nếu tôi không đặt 'Substring', nó sẽ hiển thị' DisplayName: myname' thay vì chỉ 'myname'. – Ian