Search code examples
c#.netasp.netasp.net-membership

Get the users email based on their username


Is there any built in way to get a users email address based on their username in ASP.NET 4.0? Or do I have to query the necessery tables?

I'm using this to get the logged in user:

string username = HttpContext.Current.User.Identity.Name.ToString();

Is there similar functionality to get the currently logged in users email from the database?


Solution

  • You can use the Membership.GetUser method, which takes the username. This returns a MembershipUser object, which has an Email property. So, something like this:

    var user = Membership.GetUser(username);
    var email = null;
    
    if (user != null)
    {
        email = user.Email;
    }
    

    System.Web.Security moved to the System.Web.ApplicationServices assembly in .NET 4.0 Framework, so you manually need to add a reference to that assembly to access Membership.