How to set the current users email address in ASP.NET Membership? - c#

im trying to set the current users email from within asp.net
Membership.GetUser().Email = txtEmail.Text;
Membership.UpdateUser(Membership.GetUser(User.Identity.Name));
but the next time i read the current users Email it has not changed
i read it like this
Membership.GetUser().Email

The method Membership.GetUser() returns a new user instance. Your first line is changing the Email property, and then proceeds by throwing away that change. Your second line will fetch the user again, with the old user, and update it.
The documentation for Membership.UpdateUser contains an example of updating the email property. It all boils down to passing the same User instance from Membership.GetUser() to Membership.UpdateUser.
// GetUser() without parameter returns the current logged in user.
MembershipUser u = Membership.GetUser();
u.Email = email;
Membership.UpdateUser(u);
This will cause issues if you have a custom MembershipProvider that uses the email field for identification purposes (and you login with email+password), then the user would still have User.Identity.Name equal to the old email until next login (or they get a new Forms-cookie).

Something like:
MembershipUser u = Membership.GetUser(User.Identity.Name);
u.Email = email;
System.Web.Security.Membership.UpdateUser(u);
Looks like you aren't feeding in the current user name to get user.

Related

Different username and email causes login to fail in ASP NET CORE 2.1

I'm working on a solution using ASPNET Core 2.1 with Individual autentication. I was able to implement a seed class which creates the Identity roles, the admin user and assigns a role to the admin user when the host runs for the first time. After the first run, I check the database and everything is working fine. I don't like the 'Hello, userdummy#domain.com' welcome format message so I intend to change this in the future switching from email format to something more friendly as a username. Because of that, I use a different username from email address. When I assign this different username, login fails, but if I switch back to email-email for username and email fields, login works. I want a different username from email address. Any ideas about why is that happening?
This is the piece of code in my seed class which creates a new user:
if (!_dbContext.Users.Any()) // if users table is empty
{
// instantiate a user-store class
var _userStore = new UserStore<IdentityUser>(_dbContext);
// create a new user object with a different username
var admin = new IdentityUser
{
Email = "admin#admin.com",
UserName = "Administrador" // it makes login to fail
};
try
{
// ask the store-guy to create a new admin user with the given ridiculous password :D
var result = await _userStore.CreateAsync(admin,"123456");
}
catch (System.Exception ex)
{
_logger.Error(ex, "Sorry. Something went wrong here.");
}
}
If I change the username to have the same string than the email address, I can login with no problems.
I don't want to login using username. I want to login using email address but show a different string, like a name, in welcome message.
The default convention is for an IdentityUser to login against the 'UserName` field.
You can allow an email address as a username by turning off "AllowOnlyAlphanumericUserNames"
UserManager.UserValidator = new UserValidator<TUser>(UserManager) { AllowOnlyAlphanumericUserNames = false }
See answer and usage here
As a final solution to my question, guided by the help of you guys, would be either change the validation rules for registration and sign-in forms to point to UserName (the real field being checked against User table) or try to create a claim and use it as the name to be shown in welcome and other messages. This last one would be a valid, simple and harmless workaround. Thank you all.

Checking if user's e-mail address already exists in Kentico

I am working with Kentico API and trying to check if an e-mail of a user does already exist within a website.
I tried the code below:
bool check = IsEmailUnique(String, UserInfo)
I'm not sure what UserInfo object should be passed.
This will check for an existing email address:
bool emailAlreadyExists = UserInfoProvider.IsEmailUnique(emailToCheck, MembershipContext.AuthenticatedUser);
UserInfo is whichever user you are trying to check.
MembershipContext.AuthenticatedUser is the Current User UserInfo.
If you are trying to check prior to creating a user, or just can't access the userinfo any way you can search with something like this
UserInfo user = UserInfoProvider.GetUsers().Where("Email",QueryOperator.Equals,"test#test.com").FirstObject;
bool isUnique = user == null;
If user is null then there is no user with that email address.

MembershipUser.Email returns null even when email is stored in database

my problem is, that I am not able to access the user's email, when using Membership.GetUser(username) method.
I need it when I am reset password. I receive the username in POST request.
My code looks like this:
...
System.Web.Security.MembershipUser user = System.Web.Security.Membership.GetUser(model.UserName);
if (user != null)
{
string emailAddress = user.Email;
...
I am sure that the user to whom I am trying to reset the password, has the email stored in database, but when I want to retrieve it user.Email is null.
Can somebody help me with this problem? Thank you in advance.
The methods you are using are for traditional ASP.NET membership, not SimpleMembership. Here is the way to get that information from SimpleMembership.
var user = context.UserProfiles.SingleOrDefault(u => u.UserName == username);
var email = user.Email;
You can read more about accessing and customizing UserProfile here.
There is also an article on setting up password reset for SimpleMembership here and the source code is available here.

Membership.GetUser() C# .NET

I am trying to use either the UserName or (preferably) the user ID to determine what specific user is logged into my application. My intent, is to limit the amount of content that can be uploaded to my site based on the user. Whenever the user attempts to upload a document, I want to retrieve a count of all the documents they have currently uploaded. As a test run, I just added a label to my form to try and identify the user before writing a query:
// validate user. If they are not authenticated, do not let them upload files
if (!HttpContext.Current.User.Identity.IsAuthenticated || !HttpContext.Current.User.IsInRole("Administrator"))
{
uploadLabel.Visible = false;
user.Text = Membership.GetUser().UserName; // this line should output the username
mapUpload.Visible = false;
uploadButton.Visible = false;
}
I know the authentication logic works, because all other fields are not visible when logged in. Additionally, Membership.GetUser().UserName only has a value when the user IsAuthenticated; else, I get a null pointer exception. If the code is called, then Membership.GetUser().UserName appears to be setting the label to an empty text string.
Is there another way to get information for the current logged in user? As mentioned, my ultimate goal is be able to write a query with the information:
SELECT COUNT(DocumentID) FROM Documents WHERE UserID=#UserID
Thanks in advance for any assistance.
Bic
No need to use MembershipUser event to get currently logged in user we have another simple way to get currently logged in username you just define like this in your page
string userName = Page.User.Identity.Name;
Can't you replace
user.Text = Membership.GetUser().UserName;
with
user.Text= User.Identity.Name

Get any users email

Currently I'm using to get the email for the current user.
string to;
MembershipUser username;
username = Membership.GetUser();
to = username.Email;
However when I try to pass a variable to get another users info I get an error.
Seems that Membership.Getuser() only works for the current user and not for another user.
Anyone have any suggestions on how to get the email of another user. Not the current user.
There is another method Membership.GetUser(string username) which gets a MembershipUser by username.
There is yet another one Membership.GetUser(object providerUserKey) which gets a user by whatever you've configured/coded to be providerUserKey.
Take your pick.

Categories