MVC 5 Seed Users and Roles

前端 未结 7 1897
有刺的猬
有刺的猬 2020-11-28 01:56

I have been playing about with the new MVC 5, I have a few models, controller and views setup using code first migrations.

My question is how do I seed users and ro

7条回答
  •  囚心锁ツ
    2020-11-28 02:34

    Looks like they changes the way authentication works in MVC5, changed my Global.asax.cs to the following did the trick!

    using System.Web.Mvc;
    using System.Web.Optimization;
    using System.Web.Routing;
    
    using System.Threading.Tasks;
    using MvcAuth.Models;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.Owin;
    using System.Threading;
    using Microsoft.AspNet.Identity.EntityFramework;
    
    namespace MvcAuth
    {
        public class MvcApplication : System.Web.HttpApplication
        {
            async Task AddRoleAndUser()
            {
                AuthenticationIdentityManager IdentityManager = new AuthenticationIdentityManager(
                    new IdentityStore(new ApplicationDbContext()));
    
                var role = new Role("Role1");
                IdentityResult result = await IdentityManager.Roles.CreateRoleAsync(role, CancellationToken.None);
                if (result.Success == false)
                    return false;
    
                var user = new ApplicationUser() { UserName = "user1" };
                result = await IdentityManager.Users.CreateLocalUserAsync(user, "Password1");
                if (result.Success == false)
                    return false;
    
                result = await IdentityManager.Roles.AddUserToRoleAsync(user.Id, role.Id, CancellationToken.None);
                return result.Success;
            }
    
            protected async void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
                bool x = await AddRoleAndUser();
            }
        }
    }
    

提交回复
热议问题