.Net ramblings
# Tuesday, 23 January 2007
HowTo: Correct Login Username Case
using Forms auth in an asp.net web site, with a standard Login control, i found a problem today where user 'Joe Bloggs' can log in with 'JOE BLOGGS' as his username.  this messes up my database a little because User.Identity.Name yields 'JOE BLOGGS' and i use this value in the application database. for consistency purposes i only want to use the case-correct version of the username, as it was created.

to fix this, i added the following code to my login
    protected void Login1_LoggedIn(object sender, EventArgs e)
        // correct the case of the username
        foreach(MembershipUser u in Membership.GetAllUsers())
            if(u.UserName.ToLower() == this.Login1.UserName.ToLower())
                // fix the username case
                FormsAuthentication.SetAuthCookie(u.UserName, true);

Tuesday, 23 January 2007 15:05:27 (GMT Standard Time, UTC+00:00)  #    Comments [4]  Asp.Net

Sunday, 11 March 2007 17:06:55 (GMT Standard Time, UTC+00:00)
Interesting blog, did you know you can make this code faster by calling ToUpperInvariant(), see http://msdn2.microsoft.com/en-us/library/ms973919.aspx.
Richard O'Donnell
Monday, 12 March 2007 11:00:06 (GMT Standard Time, UTC+00:00)
hi richard. thanks for the tip. however i don't just want title/proper case, i actually want the username as it is stored in the database. e.g. it could be "ABC Acme" and i want it to match exactly, i think this is the only way.
Tuesday, 25 September 2007 22:52:24 (GMT Daylight Time, UTC+01:00)
Instead of Lower (or Upper) casing the two strings and using the == operator, shouldn't you use an overload of String.Compare that does an Ordinal case-insensitive comparison instead (or one of the other options that will ignore culture and case differences, such as:

String.Compare("bob", "BOB", StringComparison.OrdinalIgnoreCase)
Wednesday, 26 September 2007 14:35:31 (GMT Daylight Time, UTC+01:00)
hi Nanm. yes you're right. although for the culture of all my apps using ToLower works fine. but best practice should be followed of course.
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