Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Username instead of Email for identity in Asp.net mvc5

Whenever I create a new application with visual studio 2013 express for web and using the individual accounts authentication and i hit the register button I notice that it implements 'Email' instead of 'Username' and the same is in the LoginViewModel as it uses Email to Sign in instead of Username. How can i change this to use Username instead of the default Email without trouble? Also i would like to know how to convert the default 'guid' that is a string type to 'id' (integer type).

like image 544
ibnhamza Avatar asked Dec 16 '14 09:12

ibnhamza


2 Answers

The linked question in the accepted answer descibes how to use Email instead of UserName, OP wanted the UserName instead of email which is what I was looking for in Identity 2.0 in an MVC project.

In case anyone else gets here from a google search it is actually very easy to do this. If you look at the register post action it is simply setting the UserName to the Email address. So.........

Add UserName to the RegisterViewModel and add it to the register view.

<div class="form-group">
        @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.UserName, new { @class = "form-control", @placeholder = "Username or email" })
        </div>
</div>

In the Register Post Action on the AccountController set the UserName to the ViewModel's UserName and the Email to the ViewModel's Email.

var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
like image 58
Hoody Avatar answered Oct 23 '22 10:10

Hoody


In order to make email as non unique:

Configure below in IdentityConfig

manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = false                
            };
like image 24
sasi kumar Avatar answered Oct 23 '22 09:10

sasi kumar