2014-11-26 23 views
10

Tôi sử dụng ASP.NET Identity 2.0 và MVC. Tôi cần phải đăng nhập tên người dùng, họ, email, vv .. trong xem. Làm thế nào để có được nó? Tôi có thể chỉ nhận được @ User.Identity nhưng không có thuộc tính của lớp người dùng của tôi.Nhận ASP.NET Identity Người dùng hiện tại Xem

//in my view, i need here my ApplicationUser class 
<div> 
@User.Identity.Name 
</div> 

//ApplicationUser class 
public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, 
CustomUserClaim> 
{ 
    public ApplicationUser() 
    { 
     this.CreatedDate = DateTime.Now; 
    } 

    public DateTime CreatedDate { get; set; } 

    public string Name { get; set; } 

    public string Surname { get; set; } 

    public string TaxOffice { get; set; } 
} 

Trả lời

15

Nếu có thuộc tính chỉ cụ thể mà bạn cần phải nhận được, bạn có thể thêm chúng như tuyên bố trong lớp ApplicationUser của bạn như ví dụ sau:

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> 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("FullName", this.FullName)); 
    // or use the ClaimTypes enumeration 
    return userIdentity; 
} 

này bị dây lên từ lớp Startup.Auth:

SessionStateSection sessionStateSection = ConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection; 
    app.UseCookieAuthentication(new CookieAuthenticationOptions 
    { 
     AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
     LoginPath = new PathString("/account/login"), 
     CookieName = sessionStateSection.CookieName + "_Application", 
     Provider = new CookieAuthenticationProvider 
     { 
      // Enables the application to validate the security stamp when the user logs in. 
      OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int> 
       (
        validateInterval: TimeSpan.FromMinutes(30), 
        regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager), 
        getUserIdCallback: (id) => (id.GetUserId<int>()) 
       ) 

     } 
    }); 

Sau đó, bạn có thể truy cập yêu cầu bồi thường (trong một cái nhìn hoặc trong một bộ điều khiển):

var claims = ((System.Security.Claims.ClaimsIdentity)User.Identity).Claims; 
var claim = claims.SingleOrDefault(m => m.Type == "FullName"); 

Không có hình thức xác thực vé ở đây.

Nếu bạn muốn các chi tiết người dùng đầy đủ có sẵn, bạn luôn có thể tạo ra một phương pháp mở rộng như sau:

public static ApplicationUser GetApplicationUser(this System.Security.Principal.IIdentity identity) 
{ 
    if (identity.IsAuthenticated) 
    { 
     using (var db = new AppContext()) 
     { 
      var userManager = new ApplicationUserManager(new ApplicationUserStore(db)); 
      return userManager.FindByName(identity.Name); 
     } 
    } 
    else 
    { 
     return null; 
    }   
} 

Và gọi nó là như thế này:

@User.Identity.GetApplicationUser(); 

Tôi muốn giới thiệu bộ nhớ đệm nếu bạn Tuy nhiên, gọi lại lần này.

+0

tuyệt vời! !! Điều này tiết kiệm cuộc sống của tôi –

4

Có hai cách bạn có thể đạt được điều này.

1) Tạo riêng CustomPrincipal bởi kế thừa giao diện IPrincipal bao gồm Name, SurnameEmail sử dụng this dụ hoặc this một của bạn.

2) Lấy chi tiết trực tiếp từ cơ sở dữ liệu và chuyển nó làm mô hình cho chế độ xem.

Phương pháp một sẽ là lựa chọn tốt nếu bạn muốn sử dụng cùng một chi tiết người dùng trong một số chế độ xem, nhưng phương pháp hai là cách đơn giản nhất để đạt được điều này. cho tôi biết nếu bạn cần bất kỳ mã trợ giúp cho phương pháp thứ hai.

+1

Đồng ý: Tôi đã sử dụng CustomPrincipal - đơn giản hơn nhiều để quấn lên những điều đó và sau đó những 'thuộc tính' của một người sử dụng có thể truy cập ở khắp mọi nơi .. –

0

để có được thông tin về người sử dụng từ bộ điều khiển bạn phải sử dụng

User.Identity.GetUserId(); 

hoặc nếu bạn muốn nhận được thông tin về người sử dụng trong lớp học của bạn

HttpContext.Current.User.Identity.GetUserId(); 
0

Bạn có thể dễ dàng sử dụng @inject gọi hàm để tiêm cả UserManagerSignInManager.

Theo quan điểm của bạn thêm dòng sau:

@inject SignInManager<YourUserIdentity> SignInManager 
@inject UserManager<YourUserIdentity> UserManager 

Sau khi tiêm, bạn sẽ có thể làm việc với UserManagerSignInManager phương pháp.Ví dụ:

@if (SignInManager.IsSignedIn(User)) 
{ 
    <a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)</a> 
} 
else 
{ 
} 

Chú ý cho đi qua các đối tượng User khi bạn cần phải tham khảo các hiện đăng nhập người dùng.

Hy vọng điều này sẽ có ích cho bất cứ ai :)

+0

Quan trọng cần lưu ý rằng @inject là một tính năng cốt lõi của ASP.Net. Khi câu hỏi được hỏi trước khi ASP.Net Core được phát hành. Điều này không thể trả lời câu hỏi của Yargicx. Nhưng là một công cụ tốt là ứng dụng web ASP.net Core – WizardHammer

Các vấn đề liên quan