.Net ramblings
# Tuesday, 24 March 2009
Asp.Net membership, correcting username case at login
if your application has users who like to log in as "JOE BLOGGS" or "joe bloggs" when their username is actually "Joe Bloggs", you might want to ensure that they login with the correct "case" of their username.  It can cause discrepancies if you refer to the current Identity.User in your web application, for example if you use the username anywhere in your database and run reports grouped on the username, you will get multiple records for each variation on the case of the username.  It is surprisingly unintuitive to solve this problem.  Firstly you would think that Asp.Net membership would take care of this itself.  Then you would think that you could determine the correct case of the username as follows:
protected void Login1_LoggedIn(object sender, EventArgs e)
string correctUsername = Membership.GetUser(this.Login1.Username).Username;
FormsAuthentication.SetAuthCookie(correctUsername , true);

but this doesn't work because the "Username" property of the MembershipUser object does not collect its value from the AspNetDB SQL database like you would expect, instead it is filled with whatever you pass it when loading the user, this must be a bug but i'm not bothered trying to convince MS.  instead, i came up with this solution below, to directly load the AspNetUser object from a Linq DataSource of the AspNetDb database (created using SqlMetal).

protected void Login1_LoggedIn(object sender, EventArgs e)
// correct the case of the username
string Username = this.Login1.UserName;
AspNetDb db = new AspNetDb();
MembershipUser memUser = Membership.GetUser(Username); // load the MembershipUser object to get the UserID
Aspnet_User aspnetUser = db.Aspnet_Users.SingleOrDefault(z => z.UserId == new Guid(memUser.ProviderUserKey.ToString()));
if(aspnetUser != null)
Username = aspnetUser.UserName;
FormsAuthentication.SetAuthCookie(Username, true);

Tuesday, 24 March 2009 16:38:48 (GMT Standard Time, UTC+00:00)  #    Comments [1]  Asp.Net

Wednesday, 25 May 2011 13:14:22 (GMT Daylight Time, UTC+01:00)
You don't need to use LINQ, but can re-retrieve the membership details via the Membership API like so:

object userKey = Membership.GetUser(this.LoginControl.UserName).ProviderUserKey;

// retrieve the username by guid, and reset the username in the cookie to ensure correct casing
string correctUsername = Membership.GetUser(userKey).UserName;
FormsAuthentication.SetAuthCookie(correctUsername, true);
Please login with either your OpenID above, or your details below.
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

[Captcha]Enter the code shown (prevents robots):

Live Comment Preview