core 2.0 Web simple use: Two, add default user, modify login mode

Source: Internet
Author: User

Background login generally lazy to use the mailbox, too long, so change to user name login.

Add Default User First

Delete or remove the Migrations directory under the data directory and the contents below

Add the class Dbinitializer to the data directory to add the default user, where the context will be added together later.

The default user rights include admin and user

Default username is admin, password is abc123

Using Microsoft.AspNetCore.Identity;
Using Rckohi.models;
Using System.Linq;

Using System.Threading.Tasks; Namespace {public class Dbinitializer {public static async Task Initialize (applicationdbcont
            Ext context, usermanager<applicationuser> usermanager,rolemanager<identityrole> RoleManager) { Context.  

            Database.ensurecreated (); if (context.   Users.any ()) {return;
        DB has been seeded} await Createdefaultuserandrole (Usermanager, rolemanager); private static Async Task Createdefaultuserandrole (usermanager<applicationuser> Usermanager, Rol
            Emanager<identityrole> rolemanager) {string roleadmin = "admin";

            String roleuser = "User";
            Await Createdefaultrole (rolemanager, roleadmin);
            Await Createdefaultrole (rolemanager, Roleuser); var user = await creatEdefaultuser (Usermanager);
            Await Adddefaultroletodefaultuser (Usermanager, roleadmin, user);
        Await Adddefaultroletodefaultuser (Usermanager, roleuser, user); 
            private static Async Task Createdefaultrole (rolemanager<identityrole> rolemanager, string role) {
        Await Rolemanager.createasync (new identityrole); private static Async task<applicationuser> Createdefaultuser (usermanager<applicationuser> userManag

            ER) {var user = new ApplicationUser {Email = "", UserName = "admin"};

            Await Usermanager.createasync (user, "abc123");
            var createduser = await Usermanager.findbyemailasync ("");
        return createduser; private static Async Task Adddefaultroletodefaultuser (usermanager<applicationuser> usermanager, string ro Le, applicationuser user) {await Usermanager.addtoroleasynC (user, role);

Modify the Applicationdbcontext class to enable model precedence

Using System.Threading.Tasks;
Using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
Using Microsoft.entityframeworkcore;
Using Rckohi.models;

    class applicationdbcontext:identitydbcontext<applicationuser>
    { Public
        Applicationdbcontext (dbcontextoptions<applicationdbcontext> options)
            : Base (options)

        Public dbset<rckohi.models.applicationuser> ApplicationUser {get; set;}

        protected override void Onmodelcreating (ModelBuilder builder)
            base. Onmodelcreating (builder);
            Customize the Identity model and override the defaults if needed.
            For example, your can rename the Identity table names and more.
            Add your customizations after calling base. Onmodelcreating (builder);}}

Modify the program class so that when you start, run Dbinitializer, and pass the database context to the past

Using Microsoft.aspnetcore;
Using Microsoft.AspNetCore.Hosting;
Using Microsoft.AspNetCore.Identity;
Using Microsoft.Extensions.DependencyInjection;
Using Microsoft.Extensions.Logging;
Using Rckohi.models;

Using System; Namespace Rckohi {public class program {public static void Main (string[] args) {//b Uildwebhost (args).

            Run ();
            var host = Buildwebhost (args); using (var scope = host. Services.createscope ()) {var services = scope.
                serviceprovider; try {var context = Services.
                    Getrequiredservice<applicationdbcontext> (); var Usermanager = Services.
                    Getrequiredservice<usermanager<applicationuser>> (); var rolemanager = Services.
                    Getrequiredservice<rolemanager<identityrole>> (); Dbinitializer.initialize (context, Usermanager, rolemanager).
   Wait ();             The catch (Exception ex) {var logger = Services.
                    Getrequiredservice<ilogger<program>> (); Logger.
                Logerror (ex, "An error occurred while seeding the database."); } host.
        Run ();
                public static Iwebhost Buildwebhost (string[] args) => webhost.createdefaultbuilder (args) . Usestartup<startup> ().
    Build (); }

When you do this, when you start, you will create a new database table and data if there is no corresponding table in the database.

Modify Login Mode

Modify Loginviewmodel to change email to username

        [DataType (Datatype.text)]
        public string UserName {get; set;}

Modify the corresponding view login.cshtml, change email to username

                <div class= "Form-group" >
                    <label asp-for= "UserName" ></label>
                    <input asp-for= "UserName" "class=" Form-control "/> <span asp-validation-for=" UserName "class=" Text-danger "

Modify the login method of the AccountController controller to change the email to username

var result = await _signinmanager.passwordsigninasync (model. UserName, model. Password, model. RememberMe, Lockoutonfailure:false);

This time, you can use the user name instead of the mailbox login.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: