本文整理汇总了C#中UserManager.CreateAsync方法的典型用法代码示例。如果您正苦于以下问题:C# UserManager.CreateAsync方法的具体用法?C# UserManager.CreateAsync怎么用?C# UserManager.CreateAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类UserManager
的用法示例。
在下文中一共展示了UserManager.CreateAsync方法的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");
}
示例2: 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 signInManager = new SignInManager<CustomUser, string>(manager,
HttpContext.GetOwinContext().Authentication);
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
{
var result = await signInManager.PasswordSignInAsync(user.UserName, password, true, false);
if (result == SignInStatus.Success)
{
return Content("Hello, " + user.FirstName + " " + user.LastName);
}
//user.FirstName = "Super";
//user.LastName = "Admin";
//await manager.UpdateAsync(user);
}
return Content("Hello, Index");
}
示例3: SetupAsync
public async Task SetupAsync()
{
_evnt = new EventViewModel
{
Title = "Title event",
Description = "Test event",
Start = "11:00",
End = "14:27",
Date = "2016-02-01"
};
var userViewModel = new LoginViewModel
{
Email = "[email protected]",
Password = "useruser",
RememberMe = false
};
var context = new DataContext();
var manager = new UserManager(new UserStore(context));
var user = await manager.FindAsync(userViewModel.Email, userViewModel.Password);
if (user == null)
{
await manager.CreateAsync(new User { Email = userViewModel.Email, UserName = userViewModel.Email }, userViewModel.Password);
}
_calendarController = new CalendarController(context);
var mockCp = new Mock<IClaimsPrincipal>();
if (user != null) mockCp.SetupGet(cp => cp.UserId).Returns(user.Id);
_calendarController.CurrentUser = mockCp.Object;
var mockAuthenticationManager = new Mock<IAuthenticationManager>();
mockAuthenticationManager.Setup(am => am.SignOut());
mockAuthenticationManager.Setup(am => am.SignIn());
_calendarController.AuthenticationManager = mockAuthenticationManager.Object;
}
示例4: Create
public async Task<ActionResult> Create(DoctorViewModel DoctorViewModel)
{
if (ModelState.IsValid)
{
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var user = new ApplicationUser() { UserName = DoctorViewModel.Email };
var result = await UserManager.CreateAsync(user, DoctorViewModel.Password);
string roleName = "Doctor";
IdentityResult roleResult;
if (!RoleManager.RoleExists(roleName))
{
roleResult = RoleManager.Create(new IdentityRole(roleName));
}
try
{
var findUser = UserManager.FindByName(DoctorViewModel.Email);
UserManager.AddToRole(findUser.Id, "Doctor");
context.SaveChanges();
}
catch
{
throw;
}
Doctor_Detail doctor = MapDoctor(DoctorViewModel);
db.Doctor_Details.Add(doctor);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(DoctorViewModel);
}
示例5: Default
public async Task<ActionResult> Default(RegisterViewModel model)
{
var context = new MyDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
// The default Validators that the UserManager uses are UserValidator and MinimumLengthValidator
// You can tweak some of the settings as follows
// This example sets the Password length to be 3 characters
UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager)
{
AllowOnlyAlphanumericUserNames = false
};
UserManager.PasswordValidator = new MinimumLengthValidator(3);
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName };
user.HomeTown = model.HomeTown;
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var authManager = HttpContext.GetOwinContext().Authentication;
var claimsIdentity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
authManager.SignIn(claimsIdentity);
return RedirectToAction("Index", "Home");
}
else
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
示例6: ConfigureUsers
public static async void ConfigureUsers(IEnumerable<InMemoryUser> users, EntityFrameworkServiceOptions options, UserManager userManager) {
using(var db = new Contexto(options.ConnectionString)) {
if(!db.Users.Any()) {
foreach(var u in users) {
var entity = new Usuario { Email = u.Claims.First(x=>x.Type==Constants.ClaimTypes.Email).Value , UserName = u.Username };
var response = await userManager.CreateAsync(entity, u.Password);
if(!response.Succeeded) {
throw new Exception("Não foi possível criar o usuario" + u.Username + response.Errors.ToString());
}
else {
var user = await userManager.FindAsync(u.Username,u.Password);
foreach(var c in u.Claims) {
await userManager.AddClaimAsync(user.Id,c);
}
await userManager.UpdateAsync(user);
}
}
db.SaveChanges();
}
}
}
示例7: Add_Should_Add_New_Login_Just_After_UserManager_CreateAsync_Get_Called
public async Task Add_Should_Add_New_Login_Just_After_UserManager_CreateAsync_Get_Called()
{
const string userName = "Tugberk";
const string loginProvider = "Twitter";
const string providerKey = "12345678";
using (IDocumentStore store = CreateEmbeddableStore())
{
using (IAsyncDocumentSession ses = store.OpenAsyncSession())
{
ses.Advanced.UseOptimisticConcurrency = true;
RavenUserStore<RavenUser> userStore = new RavenUserStore<RavenUser>(ses);
UserManager<RavenUser> userManager = new UserManager<RavenUser>(userStore);
RavenUser user = new RavenUser(userName);
UserLoginInfo loginToAdd = new UserLoginInfo(loginProvider, providerKey);
await userManager.CreateAsync(user);
await userManager.AddLoginAsync(user.Id, loginToAdd);
await ses.SaveChangesAsync();
}
using (IAsyncDocumentSession ses = store.OpenAsyncSession())
{
ses.Advanced.UseOptimisticConcurrency = true;
IUserLoginStore<RavenUser, string> userLoginStore = new RavenUserStore<RavenUser>(ses);
RavenUser user = await ses.LoadAsync<RavenUser>(RavenUser.GenerateKey(userName));
RavenUserLogin foundLogin = await ses.LoadAsync<RavenUserLogin>(RavenUserLogin.GenerateKey(loginProvider, providerKey));
// Assert
Assert.Equal(1, user.Logins.Count());
Assert.NotNull(foundLogin);
}
}
}
示例8: GetUserClaimTest
public async Task GetUserClaimTest()
{
var db = UnitTestHelper.CreateDefaultDb();
var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
var user = new IdentityUser("u1");
var result = await manager.CreateAsync(user);
UnitTestHelper.IsSuccess(result);
Assert.NotNull(user);
var claims = new[]
{
new Claim("c1", "v1"),
new Claim("c2", "v2"),
new Claim("c3", "v3")
};
foreach (Claim c in claims)
{
UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c));
}
var userClaims = new List<Claim>(await manager.GetClaimsAsync(user.Id));
Assert.Equal(3, userClaims.Count);
foreach (Claim c in claims)
{
Assert.True(userClaims.Exists(u => u.Type == c.Type && u.Value == c.Value));
}
}
示例9: btnRegistrar_Click
protected void btnRegistrar_Click(object sender, EventArgs e)
{
var manager = new UserManager();
var user = new ApplicationUser();
user.UserName = txtUserName.Text;
user.Direccion = txtDireccion.Text;
manager.CreateAsync(user);
}
示例10: AddLoginNullLoginFailsTest
public async Task AddLoginNullLoginFailsTest()
{
var db = UnitTestHelper.CreateDefaultDb();
var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
var user = new IdentityUser("Hao");
UnitTestHelper.IsSuccess(await manager.CreateAsync(user));
ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => manager.AddLoginAsync(user.Id, null)),
"login");
}
示例11: AddDuplicateLoginFailsTest
public async Task AddDuplicateLoginFailsTest()
{
var db = UnitTestHelper.CreateDefaultDb();
var mgr = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
var user = new IdentityUser("dupeLogintest");
UnitTestHelper.IsSuccess(await mgr.CreateAsync(user));
var userLogin1 = new UserLoginInfo("provider1", "p1-1");
UnitTestHelper.IsSuccess(await mgr.AddLoginAsync(user.Id, userLogin1));
UnitTestHelper.IsFailure(await mgr.AddLoginAsync(user.Id, userLogin1));
}
示例12: CreateUser
public static async Task<IdentityResult> CreateUser(PlatformUser user, string password)
{
var userManager = new UserManager<PlatformUser>(
new UserStore<PlatformUser>(new PlatformUserIdentityDbContext()));
//Allows for use of email address as username:
userManager.UserValidator = new UserValidator<PlatformUser>(userManager) { AllowOnlyAlphanumericUserNames = false };
var idResult = await userManager.CreateAsync(user, password);
return idResult;
}
示例13: WhenCeateUserAsync
public void WhenCeateUserAsync()
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_session));
var user = new ApplicationUser() { UserName = "RealUserName" };
using (var transaction = new TransactionScope())
{
var result = userManager.CreateAsync(user, "RealPassword");
transaction.Complete();
Assert.IsNull(result.Exception);
}
var actual = _session.Query<ApplicationUser>().FirstOrDefault(x => x.UserName == user.UserName);
Assert.IsNotNull(actual);
Assert.AreEqual(user.UserName, actual.UserName);
}
示例14: OnAuthenticated
/// <summary>
/// Invoked after the LTI request has been authenticated so the application can sign in the application user.
/// </summary>
/// <param name="context">Contains information about the login session as well as the LTI request.</param>
/// <param name="claims">Optional set of claims to add to the identity.</param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns>
public static async Task OnAuthenticated(LtiAuthenticatedContext context, IEnumerable<Claim> claims = null)
{
// Find existing pairing between LTI user and application user
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new LtiDb()));
var loginProvider = string.Join(":", new[] { context.Options.AuthenticationType, context.LtiRequest.ConsumerKey });
var providerKey = context.LtiRequest.UserId;
var login = new UserLoginInfo(loginProvider, providerKey);
var user = await userManager.FindAsync(login);
if (user == null)
{
var usernameContext = new LtiGenerateUserNameContext(context.OwinContext, context.LtiRequest);
await context.Options.Provider.GenerateUserName(usernameContext);
if (string.IsNullOrEmpty(usernameContext.UserName))
{
return;
}
user = await userManager.FindByNameAsync(usernameContext.UserName);
if (user == null)
{
user = new ApplicationUser { UserName = usernameContext.UserName };
var result = await userManager.CreateAsync(user);
if (!result.Succeeded)
{
return;
}
}
// Save the pairing between LTI user and application user
await userManager.AddLoginAsync(user.Id, login);
}
// Create the application identity, add the LTI request as a claim, and sign in
var identity = await userManager.CreateIdentityAsync(user, context.Options.SignInAsAuthenticationType);
identity.AddClaim(new Claim(context.Options.ClaimType, JsonConvert.SerializeObject(context.LtiRequest, Formatting.None,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }), ClaimValueTypes.String, context.Options.AuthenticationType));
if (claims != null)
{
foreach (var claim in claims)
{
identity.AddClaim(claim);
}
}
context.OwinContext.Authentication.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);
// Redirect to original URL so the new identity takes affect
context.RedirectUrl = context.LtiRequest.Url.ToString();
}
示例15: CreateUserIfNotExist
private static async System.Threading.Tasks.Task CreateUserIfNotExist(UserManager<ApplicationUser> userManager, string email, string password, string role, string loginProvider = null, string providerKey = null)
{
var user = await userManager.FindByEmailAsync(email);
if (user == null)
{
user = new ApplicationUser { UserName = email, Email = email };
var result = await userManager.CreateAsync(user, password);
if (!result.Succeeded)
{
throw new ApplicationException(string.Join("\n", result.Errors.Select(a => a.Description).ToArray()));
}
await userManager.AddToRoleAsync(user, role);
if (loginProvider != null && providerKey != null)
{
await userManager.AddLoginAsync(user, new UserLoginInfo(loginProvider, providerKey, ""));
}
}
}