简体   繁体   中英

Get user email in mvc

I have written some dirty code that retrieves user email in MVC. As you can see I´m using linq queries to retrieve info from my user database.

 List<string> emails = new List<string> {ConstantHelper.AdminEmail, ConstantHelper.OwnerEmail};
 DataContext mDataContext = new DataContext();
 User user = 
      (from allUsers in mDataContext.Users.Where(u => u.UserName == User.Identity.Name) 
        select allUsers).FirstOrDefault();
 string userEmail =
      (from allMemberships in mDataContext.Memberships.Where(u => user != null && u.UserId == user.UserId)
        select allMemberships.Email).FirstOrDefault();
 if(userEmail == null)
 {
     return false;
 }
 emails.Add(userEmail);

 //TODO: senda email

What I want to know if there is any other "shorter" or cleaner way to retrieve user email (of the user who is currently logged in)?

I googled this and found some suggestions regarding this code but I never got that to work for me.

MembershipUser u = Membership.GetUser(username);

My code works, it´s just that I would rather have cleaner code with this, any suggestions would be well appreciated :)

MembershipUser u = Membership.GetUser(username); is definitely a much better and shorter way to achieve that. You just need to write a custom membership provider to replace the default one in order to be able to customize the behavior of the GetUser and other methods to suit your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM