• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# UserStore类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



UserStore类属于命名空间,在下文中一共展示了UserStore类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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: CreateUser_Click

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

            var user = new IdentityUser() { UserName = txtUName.Text };
            user.Email = txtEmail.Text;
            user.PhoneNumber = txtPhone.Text;
            IdentityResult result = manager.Create(user, txtPass.Text);

            if (result.Succeeded)
            {
                lblStatus.Text = string.Format("User {0} was created successfully!", user.UserName);
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                Response.Redirect("/admin/main.aspx");

            }
            else
            {
                lblStatus.Text = result.Errors.FirstOrDefault();
            }
        }
开发者ID:irichardi,项目名称:assign2,代码行数:25,代码来源:register.aspx.cs


示例5: SetUp

 public void SetUp()
 {
     store = new UserStore(new LuceneDataProvider(new RAMDirectory(), Version.LUCENE_30));
     mappings = new NameValueCollection();
     middleware = new RoleMappingAuthenticationMiddleware(next) {Store = store, Settings = new NuGetWebApiSettings(NuGetWebApiSettings.DefaultAppSettingPrefix, new NameValueCollection(), mappings)};
     domainAdminUser = new ApiUserPrincipal(new GenericIdentity("T-Rex"), new [] {"Domain Administrators"});
 }
开发者ID:jjchiw,项目名称:NuGet.Lucene,代码行数:7,代码来源:RoleMappingAuthenticationMiddlewareTests.cs


示例6: 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


示例7: AddRemoveUserClaimTest

 public async Task AddRemoveUserClaimTest()
 {
     var db = UnitTestHelper.CreateDefaultDb();
     var store = new UserStore<IdentityUser>(db);
     ;
     var user = new IdentityUser("ClaimsAddRemove");
     await store.CreateAsync(user);
     Claim[] claims = {new Claim("c", "v"), new Claim("c2", "v2"), new Claim("c2", "v3")};
     foreach (Claim c in claims)
     {
         await store.AddClaimAsync(user, c);
     }
     await store.UpdateAsync(user);
     var userClaims = await store.GetClaimsAsync(user);
     Assert.Equal(3, userClaims.Count);
     await store.RemoveClaimAsync(user, claims[0]);
     Assert.Equal(3, userClaims.Count); // No effect until save changes
     db.SaveChanges();
     userClaims = await store.GetClaimsAsync(user);
     Assert.Equal(2, userClaims.Count);
     await store.RemoveClaimAsync(user, claims[1]);
     Assert.Equal(2, userClaims.Count); // No effect until save changes
     db.SaveChanges();
     userClaims = await store.GetClaimsAsync(user);
     Assert.Equal(1, userClaims.Count);
     await store.RemoveClaimAsync(user, claims[2]);
     Assert.Equal(1, userClaims.Count); // No effect until save changes
     db.SaveChanges();
     userClaims = await store.GetClaimsAsync(user);
     Assert.Equal(0, userClaims.Count);
     //Assert.Equal(0, user.Claims.Count);
 }
开发者ID:tomi85,项目名称:aspnetidentity,代码行数:32,代码来源:UserClaimsTest.cs


示例8: Post

        public HttpResponseMessage Post([FromBody]LoginPasswordUser lp)
        {
            UserStore<IdentityUser> userStore = new UserStore<IdentityUser>();

            userStore.Context.Database.Connection.ConnectionString =
                System.Configuration.ConfigurationManager.
                ConnectionStrings["GarageConnectionString"].ConnectionString;

            UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);

            var user = manager.Find(lp.login, lp.password);

            if (user != null)
            {
                //Call OWIN functionality
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                //Sign in user
                authenticationManager.SignIn(new AuthenticationProperties
                {
                    IsPersistent = false
                }, userIdentity);

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "Bruger er logget ind");
                return response;

            }
            else
            {
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Bruger findes ikke i systemet");
                return response;
            }
        }
开发者ID:henrypedersen77,项目名称:MasterKodeBase,代码行数:34,代码来源:LoginController.cs


示例9: LoginButton_Click

        protected void LoginButton_Click(object sender, EventArgs e)
        {
            // create new userStore and userManager objects
            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);

            // Find the user
            var user = userManager.Find(UserNameTextBox.Text, PasswordTextBox.Text);

            // check if username and password combo exists
            if (user != null)
            {
                // authenticate and login new user
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);

                // redirect to the Main Menu page
                Response.Redirect("~/game.aspx");
            }
            else
            {
                StatusLabel.Text = "Invalid Username or Password";
                AlertFlash.Visible = true;
            }
        }
开发者ID:Gurpanthport,项目名称:Game,代码行数:27,代码来源:Login.aspx.cs


示例10: LoginViewModel

 //private RoleManager<IdentityRole, Guid> _roleManager;
 public LoginViewModel()
 {
     _client = new CongregatioServiceClient();
     _userStore = new UserStore();
     _userManager = new UserManager<IdentityUser, Guid>(new UserStore());
        // _roleManager = new RoleManager<IdentityRole, Guid>(new RoleStore());
 }
开发者ID:karosas,项目名称:Congregatio,代码行数:8,代码来源:LoginViewModel.cs


示例11: UpdateAsync_GivenAnUpdate_UpdatesTheUser

        public async void UpdateAsync_GivenAnUpdate_UpdatesTheUser()
        {
            var applicationDatabaseConfiguration = new ApplicationDatabaseConfiguration();
            var userStore = new UserStore<User>(applicationDatabaseConfiguration);

            var user = new User
            {
                Email = "[email protected]",
                IsEmailConfirmed = true,
                PasswordHash = "PasswordHash",
                PhoneNumber = "PhoneNumber",
                IsPhoneNumberConfirmed = true,
                IsTwoFactorEnabled = false,
                LockoutEndDateUtc = null,
                IsLockoutEnabled = true,
                AccessFailedCount = 0,
                UserName = "UserName",
                IsAccountActive = true
            };

            await userStore.CreateAsync(user);

            var existingUser = await userStore.FindByNameAsync("UserName");
            existingUser.Email = "[email protected]";
            existingUser.PhoneNumber = "1234";

            await userStore.UpdateAsync(existingUser);

            var updatedUser = await userStore.FindByNameAsync("UserName");

            updatedUser.Should().NotBeNull();
            updatedUser.Email.Should().Be("[email protected]");
            updatedUser.PhoneNumber.Should().Be("1234");
        }
开发者ID:raypigott,项目名称:Identity,代码行数:34,代码来源:UserStoreTests.cs


示例12: CreateAsync_GivenNewUser_CreatesNewUserAndAssignsUserId

        public async void CreateAsync_GivenNewUser_CreatesNewUserAndAssignsUserId()
        {
            var applicationDatabaseConfiguration = new ApplicationDatabaseConfiguration();
            var userStore = new UserStore<User>(applicationDatabaseConfiguration);

            var user = new User
            {
                Email = "[email protected]",
                IsEmailConfirmed = true,
                PasswordHash = "PasswordHash",
                PhoneNumber = "PhoneNumber",
                IsPhoneNumberConfirmed = true,
                IsTwoFactorEnabled = false,
                LockoutEndDateUtc = null,
                IsLockoutEnabled = true,
                AccessFailedCount = 0,
                UserName = "UserName",
                IsAccountActive = true
            };

            await userStore.CreateAsync(user);

            var insertedUser = await userStore.FindByIdAsync(user.Id);

            insertedUser.Should().NotBeNull();
            insertedUser.Email.Should().Be("[email protected]");
        }
开发者ID:raypigott,项目名称:Identity,代码行数:27,代码来源:UserStoreTests.cs


示例13: Index

            public ActionResult Index(Login login)
            {
                // UserStore and UserManager manages data retreival. 
                UserStore<IdentityUser> userStore = new UserStore<IdentityUser>();
                UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);
                IdentityUser identityUser = manager.Find(login.UserName,
                                                                 login.Password);

                if (ModelState.IsValid)
                {
                    if (ValidLogin(login))
                    {
                        IAuthenticationManager authenticationManager
                                               = HttpContext.GetOwinContext().Authentication;
                        authenticationManager
                       .SignOut(DefaultAuthenticationTypes.ExternalCookie);

                        var identity = new ClaimsIdentity(new[] {
                                            new Claim(ClaimTypes.Name, login.UserName),
                                        },
                                            DefaultAuthenticationTypes.ApplicationCookie,
                                            ClaimTypes.Name, ClaimTypes.Role);
                        // SignIn() accepts ClaimsIdentity and issues logged in cookie.  
                        authenticationManager.SignIn(new AuthenticationProperties
                        {
                            IsPersistent = false
                        }, identity);
                        return RedirectToAction("SecureArea", "Home");
                    }
                }
                return View();
            }
开发者ID:JayOwl,项目名称:Bruteforce-Attack-Prevention,代码行数:32,代码来源:HomeController.cs


示例14: StatisticsController

 public StatisticsController()
 {
     db = new ApplicationDbContext();
     userStore = new UserStore<ApplicationUser>(db);
     userManager = new ApplicationUserManager(userStore);
     statisticsService = new StatisticsService(db);
 }
开发者ID:yuraokilka,项目名称:GymDiary,代码行数:7,代码来源:StatisticsController.cs


示例15: getWorkoutLog

        protected void getWorkoutLog()
        {
            //Get userID for viewing based off ID
             var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);
            var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
            var userIdentity = authenticationManager.User.Identity.GetUserId();
             //Try block incase an error is thrown
            try
            {
                //Connect with EF
                using (HealthLogEntities db = new HealthLogEntities())
                {
                    //Select the coloumns we need for the grid, and default sort
                    String SortString = Session["SortColumn"].ToString() + " " + Session["SortDirection"].ToString();
                    var Logs = from c in db.workoutLogs
                               where c.userID == userIdentity
                               select new { c.workoutLogID, c.userID, c.muscleGroup, c.excercise, c.wSets, c.wDate };
                    if (Logs != null)
                    {
                        //Bind the data to the gridview
                        showWorkout.DataSource = Logs.AsQueryable().OrderBy(SortString).ToList();
                        showWorkout.DataBind();
                    }

                }
            }
                //Catch any errors and redirect to the error page
             catch(Exception r)
            {
                Response.Redirect("/error.aspx");
            }
        }
开发者ID:Bennyva,项目名称:comp2007-assignment2,代码行数:33,代码来源:viewWorkout.aspx.cs


示例16: RegisterButton_Click

        protected void RegisterButton_Click(object sender, EventArgs e)
        {
            //crete new userStore and userManager objects
            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);

            var user = new IdentityUser()
            {
                UserName = UserNameTextBox.Text,
                PhoneNumber = PhoneNumberTextBox.Text,
                Email = EmailTextBox.Text
            };
            //create new user in the dbb and store the resukt
            IdentityResult result = userManager.Create(user, PasswordTextBox.Text);
            //check if succesfully registered
            if (result.Succeeded)
            {
                //authenticate and login new user
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);//store info in session

                //sign in
                authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);

                //redirect to main menu
                Response.Redirect("~/Secured/TodoList.aspx");

            }
            else
            {
                //display error in the AlertFlash div
                StatusLabel.Text = result.Errors.FirstOrDefault();
                AlertFlash.Visible = true;
            }
        }
开发者ID:Cldiaz,项目名称:COMP2007-S2016-MidTerm-200305923,代码行数:35,代码来源:Register.aspx.cs


示例17: SetUp

 public void SetUp()
 {
     DatabaseHelper.Reset();
     TestData.AddUsers();
     TestData.AdLoginsForUsers();
     _target = new UserStore<IdentityUser>();
 }
开发者ID:rioka,项目名称:Simple.Data.AspNet.Identity,代码行数:7,代码来源:When_finding_login.cs


示例18: SignIn

        protected void SignIn(object sender, EventArgs e)
        {
            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);
            IdentityUser user = userManager.Find(tbUsername.Text, tbPassword.Text);

            //if user info is found
            if (user != null)
            {
                //create cookie
                IAuthenticationManager authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                ClaimsIdentity userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                //sign in
                authenticationManager.SignIn(new AuthenticationProperties {IsPersistent = false}, userIdentity);

                var returnUrl = Request.QueryString["returnUrl"];
                //if user came from different page, redirect to that one. Otherwise redirect to main page.
                Response.Redirect(returnUrl ?? "~/default.aspx");
            }
            //if not, show error message.
            else
            {
                lblConfirmationText.Text = "Invalid username or password.";
            }
        }
开发者ID:diblaze,项目名称:Prog_2,代码行数:26,代码来源:login.aspx.cs


示例19: SeedUser

        public void SeedUser(UserSeedModel model, HomeGrownBulgariaDbContext context)
        {
            if (!context.Users.Any(u => u.UserName == model.Username))
            {
                var userStore = new UserStore<User>(context);
                var userManager = new UserManager<User>(userStore);

                var user = new User
                {
                    UserName = model.Username,
                    Email = model.Username,
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    AverageRatingReceived = ValidationConstants.AverageRatingInitialValue,
                    City = model.City
                };

                IdentityResult result = userManager.Create(user, model.Password);
                if (!result.Succeeded)
                {
                    throw new OperationCanceledException(result.Errors.First());
                }

                if (model.Role != null)
                {
                    userManager.AddToRole(user.Id, model.Role);
                }

                context.SaveChanges();
            }
        }
开发者ID:InKolev,项目名称:HomeGrownBulgaria,代码行数:31,代码来源:UsersSeeder.cs


示例20: Create

        public IIdentityManagerService Create()
        {
            var db = new IdentityDbContext<IdentityUser>(_connString);
            var userstore = new UserStore<IdentityUser>(db);
            var usermgr = new Microsoft.AspNet.Identity.UserManager<IdentityUser>(userstore);
            usermgr.PasswordValidator = new Microsoft.AspNet.Identity.PasswordValidator
            {
                RequiredLength = 3
            };
            var rolestore = new RoleStore<IdentityRole>(db);
            var rolemgr = new Microsoft.AspNet.Identity.RoleManager<IdentityRole>(rolestore);

            var svc = new Thinktecture.IdentityManager.AspNetIdentity.AspNetIdentityManagerService<IdentityUser, string, IdentityRole, string>(usermgr, rolemgr);

            var dispose = new DisposableIdentityManagerService(svc, db);
            return dispose;

            //var db = new CustomDbContext(_connString);
            //var userstore = new CustomUserStore(db);
            //var usermgr = new CustomUserManager(userstore);
            //var rolestore = new CustomRoleStore(db);
            //var rolemgr = new CustomRoleManager(rolestore);

            //var svc = new Thinktecture.IdentityManager.AspNetIdentity.AspNetIdentityManagerService<CustomUser, int, CustomRole, int>(usermgr, rolemgr);
            //var dispose = new DisposableIdentityManagerService(svc, db);
            //return dispose;
        }
开发者ID:cb55555,项目名称:Thinktecture.IdentityServer.v3.AspNetIdentity,代码行数:27,代码来源:AspNetIdentityIdentityManagerFactory.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# UserType类代码示例发布时间:2022-05-24
下一篇:
C# UserStatus类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap