Error in Web.EnsureUser(user) :- User Not Found
-
10-12-2019 - |
Question
Hey Friends I am trying to develop a web part in that I am fetching the user name.
But doing this I am getting the error that User cannot be found
.
But the main thing is that in the line where I am getting this error has the same code written in the above line and it is passed through that and gives me the error in the bellow line.
Code :
string pc = ddlPrincipleConsultant.SelectedItem.Text;
string associateconsultant = "";
string domain = System.Environment.UserDomainName;
string authoby = ddltravelcost.SelectedItem.Text;
SPUser user = web.EnsureUser(pc); //It gives me proper user name
SPUser authorizedby = web.EnsureUser(authoby);// Here I get the error
Here is the screenshot of the error.
And I also tried with below code.
SPUser user = web.AllUsers[pc];
SPUser authorizedby = web.AllUsers[authoby];
But in this it gives me error in both. Both statement do not find the users.
Please Help me to solve this prolem..
Solution
You need to include the Domain name in EnsureUser - Domain\Username
OTHER TIPS
I have the same error. I noticed that the error occurs when the username has "." like in your screenshot. To be safe, you need to get the encoded claim value for the user and pass that into the EnsureUser method. Look these articles:
Or you can just add i:0#.f|myprovider|
to the username so it looks like i:0#.f|myprovider|myuser
and pass the result into EnsureUser. In my case "myprovider" is the name of my custom membership provider.
Your code seems correct, probably the problem is somewhere else. Meanwhile, could you try this approach?
SPUser user = null;
SPUser authorizedby = null;
using (_web = web.Site.OpenWeb(web.ID))
{
user = _web.EnsureUser(pc);
}
using (_web = web.Site.OpenWeb(web.ID))
{
authorizedby = _web.EnsureUser(authoby);
}
This code is obviously over verbose, but maybe it will works.
I had to convert a possible Claims Authentication
name format back to DOMAIN\USER format to run EnsureUser
. Seems EnsureUser
will work with the claims format for existing users that have accessed the site, but not new users.
This code sample gets the email address for a user by first checking if the provided name is in claim format and converts it to DOMAIN\USER format:
using Microsoft.SharePoint.Administration.Claims;
...
string emailAddress = string.Empty;
string userLogin = userName;
if (SPClaimProviderManager.IsEncodedClaim(userName))
{
userLogin = SPClaimProviderManager.Local.ConvertClaimToIdentifier(userName);
}
SPUser user = web.EnsureUser(userLogin);
if (user != null)
{
emailAddress = user.Email;
}
Try with below code. It will worked properly.
SPUser u = SPContext.Current.Web.Users[username];