当前位置: 首页>>代码示例>>C#>>正文


C# UserManager类代码示例

本文整理汇总了C#中UserManager的典型用法代码示例。如果您正苦于以下问题:C# UserManager类的具体用法?C# UserManager怎么用?C# UserManager使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


UserManager类属于命名空间,在下文中一共展示了UserManager类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Index

        // GET: Home
        public async Task<ActionResult> Index()
        {
            var context = new ApplicationDbContext(); // DefaultConnection
            var store = new UserStore<CustomUser>(context);
            var manager = new UserManager<CustomUser>(store);

            var email = "[email protected]";
            var password = "Passw0rd";
            var user = await manager.FindByEmailAsync(email);

            if (user == null)
            {
                user = new CustomUser
                {
                    UserName = email,
                    Email = email,
                    FirstName = "Super",
                    LastName = "Admin"
                };

                await manager.CreateAsync(user, password);
            }
            else
            {
                user.FirstName = "Super";
                user.LastName = "Admin";

                await manager.UpdateAsync(user);
            }


            return Content("Hello, Index");
        }
开发者ID:shayim,项目名称:authentication-with-aspnet-identity,代码行数:34,代码来源:HomeController.cs

示例2: AddBlock

        public string AddBlock(string userId, string type)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
                var currentUser = manager.FindById(User.Identity.GetUserId());
                var blockedUser = manager.FindById(userId);

                if (type.Equals("Block"))
                {
                    currentUser.blockedList.Add(blockedUser);

                    //unfollow each person if there was any following
                    UnFollow(currentUser, blockedUser);
                    UnFollow(blockedUser, currentUser);
                }
                else  //unblock user just remove him from the list
                {
                    var block = currentUser.blockedList.Find(user => user.Id == blockedUser.Id);

                    if (block != null)
                    {
                        currentUser.blockedList.Remove(block);
                    }
                }

              //  manager.UpdateAsync(currentUser);

                var store = new UserStore<ApplicationUser>(new ApplicationDbContext());

               // store.Context.SaveChanges();
                db.SaveChanges();
                return "success";
            }
        }
开发者ID:yippee-ki-yay,项目名称:Codetweets,代码行数:35,代码来源:FeedController.cs

示例3: AddFollow

        public string AddFollow(string userId, string type)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
                var currentUser = manager.FindById(User.Identity.GetUserId());
                var followedUser = manager.FindById(userId);

                if (type.Equals("Follow"))
                {
                    currentUser.followList.Add(followedUser);
                }
                else
                {
                    UnFollow(currentUser, followedUser);
                }

                //manager.UpdateAsync(currentUser);

                var store = new UserStore<ApplicationUser>(new ApplicationDbContext());

                //store.Context.SaveChanges();
                db.SaveChanges();
                return "success";
            }
        }
开发者ID:yippee-ki-yay,项目名称:Codetweets,代码行数:26,代码来源:FeedController.cs

示例4: UserManagerService

        public UserManagerService(UserManager<AppIdentityUser> userMenager, IAuthenticationManager authenticationManager, RoleManager<IdentityRole> roleManager)
        {
            this._userMenager = userMenager;
            this._authenticationManager = authenticationManager;
            this._roleManager = roleManager;

            //Pasword validation rules

            _userMenager.UserValidator = new UserValidator<AppIdentityUser>(userMenager) { RequireUniqueEmail = true, AllowOnlyAlphanumericUserNames = false };
            _userMenager.PasswordValidator = new PasswordValidator() { RequiredLength = 6, RequireLowercase = true, RequireUppercase = true, RequireDigit = true };
            _signInMenager = new SignInManager<AppIdentityUser, string>(_userMenager, _authenticationManager);

            //_userMenager.UserLockoutEnabledByDefault = true;
            //_userMenager.DefaultAccountLockoutTimeSpan = TimeSpan.FromDays(int.MaxValue);
            //_userMenager.SetLockoutEnabled(user.Id, enabled) // Enables or disables lockout for a user 
            //Register e-mail service for identity

            _userMenager.EmailService = new EmailService();

            //Token provider for password reset
            var dataProtectionProvider = Startup.dataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                IDataProtector dataProtector = dataProtectionProvider.Create("ASP.NET Identity");
                userMenager.UserTokenProvider = new DataProtectorTokenProvider<AppIdentityUser>(dataProtector);
            }
        }
开发者ID:BeczkaPGS,项目名称:ForGrzesiekToReview,代码行数:27,代码来源:UserManagerService.cs

示例5: GetLogins

 public IEnumerable<UserLoginInfo> GetLogins()
 {
     UserManager manager = new UserManager();
     var accounts = manager.GetLogins(User.Identity.GetUserId());
     CanRemoveExternalLogins = accounts.Count() > 1 || HasPassword(manager);
     return accounts;
 }
开发者ID:menasbeshay,项目名称:ivalley-svn,代码行数:7,代码来源:Manage.aspx.cs

示例6: DevelopmentDefaultData

 public DevelopmentDefaultData(IOptions<DevelopmentSettings> options, IDataContext dataContext, UserManager<User> userManager, RoleManager<Role> roleManager)
 {
     this.settings = options.Value;
     this.dataContext = dataContext;
     this.userManager = userManager;
     this.roleManager = roleManager;
 }
开发者ID:Supermakaka,项目名称:mvc6,代码行数:7,代码来源:DevelopmentDefaultData.cs

示例7: Menu

        public ActionResult Menu()
        {
            ApplicationDbContext userscontext = new ApplicationDbContext();
            var userStore = new UserStore<ApplicationUser>(userscontext);
            var userManager = new UserManager<ApplicationUser>(userStore);

            var roleStore = new RoleStore<IdentityRole>(userscontext);
            var roleManager = new RoleManager<IdentityRole>(roleStore);

            if (User.Identity.IsAuthenticated)
            {

                if (userManager.IsInRole(this.User.Identity.GetUserId(), "Admin"))
                {
                    return PartialView("_AdminMenuView");
                }
                else if (userManager.IsInRole(this.User.Identity.GetUserId(), "Principal"))
                {
                    return PartialView("_PrincipalenuView");
                }
                else
                {
                    return PartialView("_Student");
                }
            }

            return PartialView("_Empty");
        }
开发者ID:dotnetgeorge,项目名称:SchoolBook,代码行数:28,代码来源:NavigationController.cs

示例8: AccountController

 public AccountController(IConfigurationRoot appSettings, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ILoggerFactory loggerFactory)
 {
     _appSettings = appSettings;
     _userManager = userManager;
     _signInManager = signInManager;
     _logger = loggerFactory.CreateLogger<AccountController>();
 }
开发者ID:pmalmeida,项目名称:AspNet5AngularV2,代码行数:7,代码来源:AccountController.cs

示例9: EmployeeAdminRepository

 public EmployeeAdminRepository()
 {
     AspContext = new IdentityDbContext();
     _db = new GtrackDbContext();
     UserManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
     RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>());
 }
开发者ID:nickboat,项目名称:gtrackProject,代码行数:7,代码来源:EmployeeAdminRepository.cs

示例10: AccountController

 public AccountController(
     UserManager<User> userManager,
     SignInManager<User> signInManager)
 {
     _signInManager = signInManager;
     _userManager = userManager;
 }
开发者ID:jchenga,项目名称:Orchard2,代码行数:7,代码来源:AccountController.cs

示例11: CreateAndLoginUser

 private void CreateAndLoginUser()
 {
     if (!IsValid)
     {
         return;
     }
     var manager = new UserManager();
     var user = new ApplicationUser() { UserName = userName.Text };
     IdentityResult result = manager.Create(user);
     if (result.Succeeded)
     {
         var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
         if (loginInfo == null)
         {
             Response.Redirect("~/Account/Login");
             return;
         }
         result = manager.AddLogin(user.Id, loginInfo.Login);
         if (result.Succeeded)
         {
             IdentityHelper.SignIn(manager, user, isPersistent: false);
             IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
             return;
         }
     }
     AddErrors(result);
 }
开发者ID:NikolayKostadinov,项目名称:Homeworks,代码行数:27,代码来源:RegisterExternalLogin.aspx.cs

示例12: Page_Load

        protected void Page_Load()
        {
            if (!IsPostBack)
            {
                // Определите разделы для отображения
                UserManager manager = new UserManager();
                if (HasPassword(manager))
                {
                    changePasswordHolder.Visible = true;
                }
                else
                {
                    setPassword.Visible = true;
                    changePasswordHolder.Visible = false;
                }
                CanRemoveExternalLogins = manager.GetLogins(User.Identity.GetUserId()).Count() > 1;

                // Отобразить сообщение об успехе
                var message = Request.QueryString["m"];
                if (message != null)
                {
                    // Извлечь строку запроса из действия
                    Form.Action = ResolveUrl("~/Account/Manage");

                    SuccessMessage =
                        message == "ChangePwdSuccess" ? "Пароль изменен."
                        : message == "SetPwdSuccess" ? "Пароль задан."
                        : message == "RemoveLoginSuccess" ? "Учетная запись удалена."
                        : String.Empty;
                    successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
                }
            }
        }
开发者ID:1extra,项目名称:prog2015,代码行数:33,代码来源:Manage.aspx.cs

示例13: CreateUser

        public static ApplicationUser CreateUser(UserManager<ApplicationUser> userManager, string email, string firstName, string lastName,
           string password, bool lockOutEnabled)
        {
            var user = userManager.FindByName(email);

            if (user == null)
            {
                user = new ApplicationUser
                {
                    UserName = email,
                    Email = email,
                    FirstName = firstName,
                    LastName = lastName,
                    EmailConfirmed = true
                };
                try
                {
                    userManager.Create(user, password);
                }
                catch (Exception ex)
                {
                    Log4NetHelper.Log("Error creating Admin User", LogLevel.ERROR, "AspNetUser", 1, "none", ex);
                }
                userManager.SetLockoutEnabled(user.Id, lockOutEnabled);
            }
            return user;
        }
开发者ID:rswetnam,项目名称:GoodBoating,代码行数:27,代码来源:SeedServices.cs

示例14: btnRegister_Click

        protected void btnRegister_Click(object sender, EventArgs e)
        {
            try
            {
                // Default UserStore constructor uses the default connection string named: DefaultConnection
                var userStore = new UserStore<IdentityUser>();
                var manager = new UserManager<IdentityUser>(userStore);

                var user = new IdentityUser() { UserName = txtUsername.Text };

                IdentityResult result = manager.Create(user, txtPassword.Text);

                if (result.Succeeded)
                {
                    //lblStatus.Text = string.Format("User {0} was created successfully!", user.UserName);
                    //lblStatus.CssClass = "label label-success";
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                    Response.Redirect("admin/main-menu.aspx");
                }
                else
                {
                    lblStatus.Text = result.Errors.FirstOrDefault();
                    lblStatus.CssClass = "label label-danger";
                }
            }
            catch (Exception q)
            {
                Response.Redirect("/error.aspx");
            }
        }
开发者ID:JamesIsNinja,项目名称:comp2007lab4,代码行数:32,代码来源:register.aspx.cs

示例15: ManageController

 public ManageController(
 UserManager<ApplicationUser> userManager,
 SignInManager<ApplicationUser> signInManager,)
 {
     _userManager = userManager;
     _signInManager = signInManager;
 }
开发者ID:yorkerossington,项目名称:YRADMIN_GIT,代码行数:7,代码来源:ManageController.cs


注:本文中的UserManager类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。