I might be overlooking something obvious here, but is it possible to return a Sitecore user with the username in the capitalisation they used when registering?
At the moment the username will be disp开发者_C百科layed as whatever the user typed when they logged in, but I'd like to be able to get the original string.
I'm using User user = User.FromName(domainUser, false);
UPDATE: This is what I ended up with after Yan's excellent answer:
// get the MembershipUser object normally by name
var initialUser = Membership.GetUser(domainUser, false);
if (initialUser != null)
{
// get the same MembershipUser by Id - in this case it retuns username in correct case
initialUser = Membership.GetUser(initialUser.ProviderUserKey, false);
}
// get the Sitecore user from the username in correct case
Sitecore.Security.Accounts.User user = Sitecore.Security.Accounts.User.FromName(initialUser.UserName, false);
Thanks,
Annelie
That's an interesting question, and it was fun to dig into this deeper.
The line of code you mentioned doesn't actually go to the security database to get the user. It only creates a User object with the name you provided.
You can refer to the lower-level ASP.NET class System.Web.Security.Membership
. It contains the method GetUser
, which is overloaded a number of times. The trick is that its overloaded version which accepts username as a parameter behaves the same as User.FromName
. I mean it doesn't return actual UserName
from the underlying SQL table, but uses the username you passed in parameters to GetUser
method. It still works correctly - all comparisons are done in lowercase.
So, if you DO need to get real case of the user name, you can use one of the methods which actually query the underlying SQL source for the UserName field. For instance, GetUser(object, bool)
, which gets the user by UserId:
// get the MembershipUser object normally by name
var user = Membership.GetUser(@"sitecore\admin", false);
if (user != null)
{
// get the same MembershipUser by Id - in this case it retuns username in correct case
user = Membership.GetUser(user.ProviderUserKey, false);
// use the user.UserName value as you wish
Response.Write(user.UserName);
}
As you can see, it is 2 calls to the database instead of 1 for Membership.GetUser(username)
and instead of 0 for User.FromName(username)
.
Alternatively, if you know for sure the user has email, and you know this email, you can use Membership.GetUserNameByEmail(email)
method.
精彩评论