本文整理汇总了C#中UserManager.FindByIdAsync方法的典型用法代码示例。如果您正苦于以下问题:C# UserManager.FindByIdAsync方法的具体用法?C# UserManager.FindByIdAsync怎么用?C# UserManager.FindByIdAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类UserManager
的用法示例。
在下文中一共展示了UserManager.FindByIdAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Index
public async Task<ActionResult> Index()
{
if (this.User.Identity.IsAuthenticated)
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));
var appUser = await manager.FindByIdAsync(this.User.Identity.GetUserId());
IQueryable<Game> games = from membership in db.GameMemberships
where membership.ApplicationUserID == appUser.Id
join game in db.Games on membership.GameID equals game.ID
select game;
var adminRole = await db.Roles.FirstOrDefaultAsync(role => role.Name == "Admin");
this.ViewBag.Games = await games.ToListAsync();
this.ViewBag.Claims = await manager.GetClaimsAsync(appUser.Id);
this.ViewBag.Roles = await manager.GetRolesAsync(appUser.Id);
}
return View();
}
示例2: Create
public async Task<ActionResult> Create([Bind(Include = "ID,Name,Visibility")] Game game)
{
if (ModelState.IsValid)
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));
var appUser = await manager.FindByIdAsync(this.User.Identity.GetUserId());
db.Games.Add(game);
await manager.AddClaimAsync(appUser.Id, new Claim("GameMembership", game.ID.ToString()));
await manager.AddClaimAsync(appUser.Id, new Claim("GameOwnership", game.ID.ToString()));
await manager.AddClaimAsync(appUser.Id, new Claim("GameMaster", game.ID.ToString()));
var membership = new GameMembership()
{
Game = game,
ApplicationUser = appUser,
Roles = "Owner",
};
db.GameMemberships.Add(membership);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(game);
}
示例3: Index
public ActionResult Index()
{
if (User.Identity.IsAuthenticated)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
ApplicationUser user = userManager.FindByIdAsync(User.Identity.GetUserId()).Result;
if (UserManager.IsInRole(user.Id, "Admin"))
{
return RedirectToAction("Index", "Admins");
}
else if (UserManager.IsInRole(user.Id, "Profesor"))
{
return RedirectToAction("Index", "Profesors");
}
else if (UserManager.IsInRole(user.Id, "Referada"))
{
return RedirectToAction("Index", "Referadas");
}
else if (UserManager.IsInRole(user.Id, "Dekan"))
{
return RedirectToAction("Index", "Dekans");
}
else if (UserManager.IsInRole(user.Id, "Procelnik"))
{
return RedirectToAction("Index", "Procelniks");
}
}
return View();
}
示例4: ChangePassword
public async Task<JsonData> ChangePassword(ChangePasswordModel changePass)
{
try
{
var db = new DataContext();
var userMan = new UserManager<MyUser>(new UserStore<MyUser>(db));
userMan.UserValidator = new UserValidator<MyUser>(userMan)
{
AllowOnlyAlphanumericUserNames =
false
};
var user = await userMan.FindByIdAsync(User.Identity.GetUserId());
if (user == null) throw new Exception("please check your old password");
var newPassword = changePass.NewPassword;
var result = await userMan.RemovePasswordAsync(user.Id);
if (!result.Succeeded) throw new Exception(string.Join(", ", result.Errors));
var result2 = await userMan.AddPasswordAsync(user.Id, newPassword);
if (!result2.Succeeded) throw new Exception(string.Join(", ", result2.Errors));
return DataHelpers.ReturnJsonData(null, true, "Password changed successful");
}
catch (Exception e)
{
return DataHelpers.ExceptionProcessor(e);
}
}
示例5: SendAsync
protected async override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
var query = request.RequestUri.ParseQueryString();
if (query.AllKeys.Any(x => x == "token"))
{
var jwt = ((JwtSecurityToken)new JwtSecurityTokenHandler().ReadToken(query.GetValues("token")[0]));
var userId = jwt.Claims.FirstOrDefault(x => x.Type.Equals("nameid")).Value;
if (userId != null)
using (var context = DatabaseContext.Create())
using (var userManager = new UserManager(new UserStore<User>(context)))
{
User currentUser = null;
if ((currentUser = await userManager.FindByIdAsync(userId)) != null)
{
var identity = await currentUser.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);
var principal = new GenericPrincipal(identity, (await userManager.GetRolesAsync(currentUser.Id)).ToArray());
Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
}
}
}
return await base.SendAsync(request, cancellationToken);
}
示例6: GetUser
public async Task<MyUser> GetUser(string userId)
{
var db = new DataContext();
var userMan = new UserManager<MyUser>(new UserStore<MyUser>(db));
var currentUser = await userMan.FindByIdAsync(userId);
return currentUser;
}
示例7: Index
//
// GET: /Users/
public async Task<ActionResult> Index()
{
ApplicationDbContext db = new ApplicationDbContext();
var userStore = new UserStore<ApplicationUser>(db);
var userManager = new UserManager<ApplicationUser>(userStore);
var user = await userManager.FindByIdAsync(User.Identity.GetUserId());
ViewBag.RoleNames = await UserManager.GetRolesAsync(user.Id);
return View(user);
}
示例8: Profile
public ActionResult Profile()
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ApplicationDbContext.Create()));
var currentUser = manager.FindByIdAsync(User.Identity.GetUserId<string>()).Result;
ViewBag.HomeTown = currentUser.HomeTown;
ViewBag.FirstName = currentUser.UserInfo.FirstName;
return View();
}
示例9: Email
public static string Email(this ClaimsPrincipal user, UserManager<ApplicationUser> userManager)
{
if (user.Identity.IsAuthenticated)
{
var appUser = userManager.FindByIdAsync(user.Identity.GetUserId()).Result;
return appUser.Email;
}
return string.Empty;
}
示例10: PhoneNumber
public static string PhoneNumber(this ClaimsPrincipal user, UserManager<ApplicationUser> userManager)
{
if (user.Identity.IsAuthenticated)
{
var appUser = userManager.FindByIdAsync(user.Identity.GetUserId()).Result;
return appUser.PhoneNumber;
}
return "";
}
示例11: Create
public async Task<GameResult> Create([FromBody]GameResult result)
{
if (result == null)
{
throw new ArgumentNullException("game");
}
GameVisibility visibility;
if (!Enum.TryParse(result.Visibility, out visibility))
{
throw new ArgumentException("game.Visibility is not valid");
}
var game = new Game()
{
Name = result.Name,
Visibility = visibility,
};
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));
var appUser = await manager.FindByIdAsync(this.User.Identity.GetUserId());
db.Games.Add(game);
await manager.AddClaimAsync(appUser.Id, new Claim("GameMembership", game.ID.ToString()));
await manager.AddClaimAsync(appUser.Id, new Claim("GameOwnership", game.ID.ToString()));
await manager.AddClaimAsync(appUser.Id, new Claim("GameMaster", game.ID.ToString()));
var membership = new GameMembership()
{
Game = game,
ApplicationUser = appUser,
Roles = "Owner",
};
db.GameMemberships.Add(membership);
await db.SaveChangesAsync();
result.GameId = game.ID;
return result;
}
示例12: Index
// GET: Profile
public async Task<ActionResult> Index(ManageController.ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageController.ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageController.ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageController.ManageMessageId.SetTwoFactorSuccess ? "Your two factor provider has been set."
: message == ManageController.ManageMessageId.Error ? "An error has occurred."
: message == ManageController.ManageMessageId.AddPhoneSuccess ? "The phone number was added."
: message == ManageController.ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var currentUser = await manager.FindByIdAsync(User.Identity.GetUserId());
var model = new IndexViewModel
{
HasPassword = HasPassword(),
PhoneNumber = await UserManager.GetPhoneNumberAsync(User.Identity.GetUserId()),
TwoFactor = await UserManager.GetTwoFactorEnabledAsync(User.Identity.GetUserId()),
Logins = await UserManager.GetLoginsAsync(User.Identity.GetUserId()),
BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(User.Identity.GetUserId()),
FirstName = currentUser.UserProfile.FirstName,
LastName = currentUser.UserProfile.LastName,
Email = currentUser.UserProfile.Email,
Address1 = currentUser.UserProfile.Address1,
City = currentUser.UserProfile.City,
ProvState = currentUser.UserProfile.ProvState,
PostZipCode = currentUser.UserProfile.PostZipCode,
Country = currentUser.UserProfile.Country,
Telephone = currentUser.UserProfile.Telephone,
AvatarImgUrl = currentUser.UserProfile.AvatarImgUrl,
};
ViewBag.UserId = User.Identity.GetUserId();
return View(model);
}
示例13: Me
public async Task<ActionResult> Me()
{
using (var ctx = new SportDataContext())
{
var userManager = new UserManager<User>(new UserStore<User>(ctx));
var user = await userManager.FindByIdAsync(User.Identity.GetUserId());
await ctx.Entry(user).Collection(u => u.Licenses).LoadAsync();
var license = user.Licenses.FirstOrDefault(l => l.Season == 2014);
return Json(new
{
found = user != null,
lastName = user != null ? user.LastName : "",
firstName = user != null ? user.FirstName : "",
license = license!=null? license.Number : "",
userId = user!=null ? user.Id : ""
},
JsonRequestBehavior.AllowGet);
}
}
示例14: InitializeUser
/// <summary>
/// Initializes the user.
/// </summary>
public void InitializeUser(SessionAuthUser authUser)
{
AuthUser = authUser;
if ((AuthUser == null) || (AuthUser.SystemUserID == 0))
{
var store = new UserStore<ApplicationUser>(new AuthenticationDbContext());
var userManager = new UserManager<ApplicationUser>(store);
ApplicationUser user = userManager.FindByIdAsync(User.Identity.GetUserId()).Result;
if (user == null)
return;
string nickname = user.UserName;
if (nickname.Contains(" "))
nickname = user.UserName.Substring(0, user.UserName.IndexOf(" "));
if (nickname.Length > 30)
nickname = nickname.Substring(0, 30);
using (AuthManager authManager = PublicConfigurationSettings.GetAuthManager.Invoke())
{
authManager.RegisterUser(User.Identity.GetUserId(), nickname,
user.UserName, user.PhoneNumber, user.Email);
AuthUser = authManager.GetAuthUser(User.Identity.GetUserId());
}
}
ViewBag.AuthUser = AuthUser;
bool hasClient = PublicLogicManager.Client.CurrentUserHasClient();
ViewBag.HasClient = hasClient;
ViewBag.UserNickname = AuthUser.Nickname;
if (hasClient)
{
ClientData client = PublicLogicManager.Client.LoadClientModel(false);
ViewBag.ClientName = client.CompanyName;
ViewBag.Client = client;
ViewBag.Build = BuildNumber;
}
PerformClientLogic();
}
示例15: EnsureDatabaseAsync
public async Task EnsureDatabaseAsync()
{
await MigrateDatabaseAsync(ServiceProvider);
_userManager = ServiceProvider.GetService<UserManager<ApplicationUser>>();
var roleManager = ServiceProvider.GetService<RoleManager<IdentityRole>>();
await EnsureUsersAsync(false);
Context = ServiceProvider.GetRequiredService<ApplicationDbContext>();
//var userStore = new UserStore<ApplicationUser>(context);
////var roleManager = new RoleManager<IdentityRole>();
//var userManager = new UserManager<ApplicationUser>(
// , );
EnsureDatabaseExists();
Context.Database.EnsureCreated();
// Add Mvc.Client to the known applications.
_productsCrud = new CrudBase<Product, int>(
Context, Context.Products, p => p.ProductId);
_ordersCrud = new CrudBase<Order, int>(
Context, Context.Orders, p => p.Id);
var customersCrud = new CrudBase<Customer, int>(
Context, Context.Customers, p => p.CustomerId);
//Action<string, double, int?, DateTime?, string> prod = (name, price, customerId, dateCreated, cratedByUserId) =>
//{
// productId = Prod(productsCrud, productId, name, price, customerId, dateCreated, cratedByUserId);
//};
Action<string, string, string> cust = (guid, firstName, lastName) =>
{
customersCrud.EnsureEntity(
guid, customer =>
{
customer.FirstName = firstName;
customer.LastName = lastName;
});
};
cust("6c13ec25-b9cf-4c99-87e7-13a45a034342", "Harry", "Whitburn");
cust("0e941f32-8ae1-4eae-875a-f748bae3ce2a", "Nick", "Lawden");
cust("134bd420-f64a-40db-bbe4-0b9a9ff3eb01", "Emil", "Roijer");
Context.SaveChanges();
Prod("00d5c0b0-738d-41ff-86d4-dca84da1d4d5", "Apple number1", 10, null, null);
Prod("cd4c554d-3ca2-49aa-9286-08abacba3fa0", "Apple number1", 10, 1, null, "1");
Prod("d100c753-3335-439c-88db-b8d9b6c09cc8", "Orange number1", 20, null, null);
Prod("da93b8a4-4378-4ce0-918e-653f1bd4acaf", "Peanut butter number1", 25, 2, null);
Prod("fe208521-4a77-4b09-94c2-2f08a4dd8872", "xApple number2", 10, 1, null);
Prod("844fbc16-3d77-4421-9498-aa65300bc789", "xOrange number2", 20, 2, null);
Prod("78509968-0073-4c57-8774-ec0d58ea7ff3", "xPeanut butter number2", 25, 2, null);
Prod("18b8c4e7-48a2-40c7-bea8-1d1879bf852e", "xApple number2", 10, 1, null);
Prod("e5ab744c-441c-447b-ae92-055b1bce5541", "xOrange number2", 20, 2, null);
Prod("3a5476b1-7dd8-40b0-a6ce-b6bd3127da6f", "xPeanut butter number2", 25, 2, null);
Prod("633a125c-1fe2-4f06-859d-a8d8fd52eb11", "xApple number2", 10, 1, null);
Prod("27eea6ff-c4aa-44a0-84fe-32b0e13beec4", "xOrange number2", 20, 2, null);
Prod("dcdc6836-3b44-41c5-8ade-792e39ce2112", "xPeanut butter number2", 25, 2, null);
Prod("fdc3139d-8585-4b34-b815-13598bf55791", "xApple number2", 10, 1, null);
Prod("46b058b2-dd55-4741-9ee0-99c63c4bd94a", "xOrange number2", 20, 2, null);
Prod("11c0e3e5-c5d7-4ff5-ba6c-a54b77f91d1b", "xPeanut butter number2", 25, 2, null);
Prod("796b6b1d-2d6d-413c-bcab-2659c0fdf02f", "Apple number3", 10, 1, null);
Prod("5f928f2f-bc1b-4e73-a0d8-20c36f817342", "Orange number3", 20, 2, null);
Prod("f4fa623d-f412-4b68-8a26-17cfa16cb0a0", "Peanut butter number3", 25, 2, null);
Prod("8f81d6ab-4c8f-4800-aea0-3cb1ca116fc6", "Apple number4", 10, 1, null);
Prod("f2b8032f-c8ac-406f-8038-939201771901", "Orange number4", 20, 2, null);
Prod("dc872dbf-956c-43aa-aba4-e75395af7d83", "Peanut butter number4", 25, 2, null);
Prod("4ca16ce0-1466-4ba6-a69b-5465ed0a4b1d", "Apple number5", 10, 1, null);
Prod("66cc487b-2eb1-470b-98c8-03ee913d860e", "Orange number5", 20, 2, null);
Prod("e77e6589-1dba-4c8b-97b1-1564056ddf10", "Peanut butter number5", 25, 2, null);
Prod("183946f3-41a9-4140-a1cb-b328e3a778d1", "Apple number6", 10, 1, null);
Prod("2995edec-ec1b-42ed-aa97-1e68a9ef765c", "Orange number6", 20, 2, null);
Prod("a78204ae-169a-4d30-936b-034cda5abd0f", "Peanut butter number6", 25, 2, null);
Context.SaveChanges();
Order("31d57282-4824-4441-9bd0-49588b952728", "First order", 1);
Order("fc41cc01-6dc3-4ca5-88a4-c4a463cd6316", "Second order", 1);
Order("f1379562-c779-43bc-a507-71a8506ca8c9", "Third order", 1);
Context.SaveChanges();
await EnsureUsersAsync(true);
await roleManager.CreateAsync(new IdentityRole("Admin"));
await roleManager.CreateAsync(new IdentityRole("User"));
await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync("1"), "Admin");
await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync("1"), "User");
await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync("2"), "User");
}