本文整理汇总了C#中RoleManager.FindById方法的典型用法代码示例。如果您正苦于以下问题:C# RoleManager.FindById方法的具体用法?C# RoleManager.FindById怎么用?C# RoleManager.FindById使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类RoleManager
的用法示例。
在下文中一共展示了RoleManager.FindById方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: deleteRole
public ActionResult deleteRole(string roleID)
{
ajaxReturnData data = new ajaxReturnData();
try
{
using (ApplicationDbContext DB = new ApplicationDbContext())
{
ApplicationUser user = new ApplicationUser();
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(DB));
IdentityRole role = roleManager.FindById(roleID);
string name = role.Name;
roleManager.Delete(role);
data.statusCode = (int)statusCodes.successRun;
data.message = "Role '" + name + "' removed";
}
}
catch (Exception ex)
{
data.statusCode = (int)statusCodes.fail;
data.message = "Failed to remove role; Error is: " + ex.Message;
}
return Json(data);
}
示例2: Details
public void Details(AspNetUserDetailsViewModel mdl)
{
var ctx = new ApplicationDbContext();
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(ctx));
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ctx));
//if(userManager.IsInRole(mdl.User.Id, "Admin"))
//{
// mdl.RoleId = RoleManager.FindByName("Admin")?.Id;
//}
//if(userManager.IsInRole(mdl.User.Id, "NetUser"))
//{
// mdl.RoleId = RoleManager.FindByName("NetUser")?.Id;
//}
var role = RoleManager.FindById(mdl.RoleId);
var roles = RoleManager.Roles.ToList();
foreach(var item in roles)
{
userManager.RemoveFromRole(mdl.User.Id, item.Name);
}
userManager.AddToRole(mdl.User.Id, role.Name);
}
示例3: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
//context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
AuthContext _auth = new AuthContext();
UserManager<IdentityUser> _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_auth));
RoleManager<IdentityRole> _roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_auth));
AuthRepository _repo = new AuthRepository();
IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
var userIdentity = await _userManager.CreateIdentityAsync(user, context.Options.AuthenticationType);
foreach (IdentityUserRole role in user.Roles)
{
var iRole = _roleManager.FindById(role.RoleId);
userIdentity.AddClaim(new Claim(ClaimTypes.Role, iRole.Name));
}
userIdentity.AddClaim(new Claim("sub", context.UserName));
userIdentity.AddClaim(new Claim("role", "user"));
var ticket = new AuthenticationTicket(userIdentity, null);
context.Validated(ticket);
}
示例4: getRoleName
private string getRoleName(string id)
{
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var role = RoleManager.FindById(id);
return role.Name;
}
示例5: ClearUserRoles
public void ClearUserRoles(string userId)
{
var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
var user = um.FindById(userId);
var currentRoles = new List<IdentityUserRole>();
currentRoles.AddRange(user.Roles);
foreach (var role in currentRoles)
{
var r = rm.FindById(role.RoleId);
um.RemoveFromRole(userId, r.Name);
}
}
示例6: AddToRole
public void AddToRole(string role, string employee)
{
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var user = UserManager.FindByName(employee);
var userRoles = user.Roles.ToList();
//user.Roles.Remove(roles);
foreach (var Role in userRoles)
{
var roleName = roleManager.FindById(Role.RoleId);
UserManager.RemoveFromRole(user.Id, roleName.Name);
}
UserManager.AddToRole(user.Id, role);
}
示例7: AssignRole
public async Task<ActionResult> AssignRole(string id = "default")
{
if (id != "default")
{
var User = _identityDb.Users.Find(id);
ViewBag.User = User;
var userStore = new UserStore<ApplicationUser>(_identityDb);
var userManager = new UserManager<ApplicationUser>(userStore);
var roleStore = new RoleStore<IdentityRole>(_identityDb);
var roleManager = new RoleManager<IdentityRole>(roleStore);
ViewBag.Role = roleManager.FindById(User.Roles.FirstOrDefault().RoleId).Name;
//await ViewBag.Roles.Add(roleManager.FindById(User.Roles.FirstOrDefault().RoleId));
ViewBag.UserNames = _identityDb.Users.Select(u => u.UserName);
ViewBag.RoleNames = _identityDb.Roles.Select(r => r.Name);
return View();
}
Response.StatusCode = 404;
return View();
}
示例8: GetAllUsers
public ActionResult GetAllUsers()
{
using (var userManager = HttpContext.GetOwinContext().Get<ApplicationUserManager>())
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
var users = userManager.Users.ToList();
List<dynamic> response = new List<dynamic>();
foreach (var user in users)
{
var role = user.Roles.FirstOrDefault();
var roleObj = role != null ? roleManager.FindById(role.RoleId) : null;
var roleName = roleObj != null ? roleObj.Name : "";
response.Add(new
{
Id = user.Id,
UserName = user.UserName,
RoleName = roleName
});
}
return Json(new { Result = "OK", Data = response });
}
}
示例9: DeleteRoleForUser
public ActionResult DeleteRoleForUser(string userName = null, string roleName = null)
{
if ((!string.IsNullOrWhiteSpace(userName)) || (!string.IsNullOrWhiteSpace(roleName)))
{
List<string> userRoles;
using (var context = new ApplicationDbContext())
{
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
var user = userManager.FindByName(userName);
if (user == null)
{
throw new Exception("User not found!");
}
if (userManager.IsInRole(user.Id, roleName))
{
userManager.RemoveFromRole(user.Id, roleName);
context.SaveChanges();
}
var userRoleIds = (from r in user.Roles select r.RoleId);
userRoles = (from id in userRoleIds
let r = roleManager.FindById(id)
select r.Name).ToList();
}
ViewBag.UserName = userName;
ViewBag.RolesForUser = userRoles;
return View("ViewUserRoles");
}
else
{
return View("Index");
}
}
示例10: Login
public bool Login()
{
var manager = new UserManager();
ApplicationUser user = manager.Find(_username, _password);
if (user != null)
{
System.Web.HttpContext.Current.Session["New"] = user.UserName;
System.Web.HttpContext.Current.Session["SESSIONID"] = Guid.NewGuid();
String sessionID = HttpContext.Current.Session.SessionID;
System.Diagnostics.Debug.WriteLine("Session ID:" + sessionID);
System.Diagnostics.Debug.WriteLine("User GUID:" + System.Web.HttpContext.Current.Session["SESSIONID"]);
IdentityHelper.SignIn(manager, user, _rememberMe);
//IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>());
var Test1 = roleManager.FindById(user.Id);
var Test2 = roleManager.FindByName(user.UserName);
//IdentityResult addRoles = manager.AddToRole(storedUser.Id, newRole);
//var Test3 = manager.GetRoles(user.UserName);
//var Test4 = manager.IsInRole(user.Id,"Administrator");
//var Test5 = manager.GetRoles(user.Id);
//var Test = HttpContext.Current.User.IsInRole("Administrator");
//Retrieve Role ID
try
{
//Retrieve from database
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand();
//SqlDataReader reader;
string queryString = "SELECT * FROM AspNetUserRoles where UserId='" + user.Id + "'";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, conn);
DataSet ds = new DataSet();
conn.Open();
adapter.Fill(ds);
conn.Close();
var Role_ID = ds.Tables[0].Rows[0][1].ToString();
string fetchRoleName = "SELECT * FROM AspNetRoles where Id='" + Role_ID + "'";
SqlDataAdapter fetchRoleNameadapter = new SqlDataAdapter(fetchRoleName, conn);
DataSet fetchRoleNameds = new DataSet();
conn.Open();
fetchRoleNameadapter.Fill(fetchRoleNameds);
conn.Close();
var Role_Name = fetchRoleNameds.Tables[0].Rows[0][1].ToString();
System.Diagnostics.Debug.WriteLine("Role_Name:" + Role_Name);
if (Role_Name == "Administrator")
{
System.Web.HttpContext.Current.Session["AdminFlag"] = "True";
}
else
{
System.Web.HttpContext.Current.Session["AdminFlag"] = null;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception:" + ex);
}
System.Diagnostics.Debug.WriteLine("Session Admin Flag:" + System.Web.HttpContext.Current.Session["AdminFlag"]);
return true;
}
return false;
}
示例11: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
//try {
var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
if (allowedOrigin == null) allowedOrigin = "*";
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
if (!user.EmailConfirmed)
{
context.SetError("invalid_grant", "User did not confirm email.");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
user.Roles.ToList().ForEach(r =>
{
var role = roleManager.FindById(r.RoleId);
identity.AddClaim(new Claim(ClaimTypes.Role, role.Name));
});
identity.AddClaim(new Claim("sub", context.UserName));
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{
"as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
},
{
"userName", context.UserName
}
});
var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
//}
//catch (Exception ex)
//{
// throw;
// }
}
示例12: removeRole
public async Task<ActionResult> removeRole(string userID, string roleID)
{
ajaxReturnData data = new ajaxReturnData();
try
{
using (ApplicationDbContext DB = new ApplicationDbContext())
{
ApplicationUser user = new ApplicationUser();
var store = new UserStore<ApplicationUser>(DB);
UserManager<ApplicationUser> um = new UserManager<ApplicationUser>(store);
user = um.FindById(userID);
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(DB));
IdentityRole role = RoleManager.FindById(roleID);
if (user.UserName == "[email protected]" && role.Name == "admin") {
data.statusCode = (int)statusCodes.fail;
data.message = "I'm sorry Dave, I'm afraid I can't do that";
}
else
{
await store.RemoveFromRoleAsync(user, role.Name);
await store.UpdateAsync(user);
data.statusCode = (int)statusCodes.successRun;
data.message = "Role '" + role.Name + "' removed from user '" + user.UserName + "'";
}
}
}
catch (Exception ex)
{
data.statusCode = (int)statusCodes.fail;
data.message = "Failed to remove role from user; Error is: " + ex.Message;
}
return Json(data);
}
示例13: addRole
public async Task<ActionResult> addRole(string userID, string roleID)
{
ajaxReturnData data = new ajaxReturnData();
try
{
using (ApplicationDbContext DB = new ApplicationDbContext())
{
ApplicationUser user = new ApplicationUser();
var store = new UserStore<ApplicationUser>(DB);
UserManager<ApplicationUser> um = new UserManager<ApplicationUser>(store);
user = um.FindById(userID);
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(DB));
IdentityRole role = RoleManager.FindById(roleID);
await store.AddToRoleAsync(user, role.Name);
await store.UpdateAsync(user);
data.statusCode = (int)statusCodes.successRun;
data.message = "Role '" + role.Name + "' added to user '" + user.UserName + "'";
}
}
catch(Exception ex)
{
data.statusCode = (int)statusCodes.fail;
data.message = "Failed to add role to user; Error is: "+ ex.Message;
}
return Json(data);
}
示例14: LogIn
protected void LogIn(object sender, EventArgs e)
{
//System.Diagnostics.Debug.WriteLine("Outside Session ID:" + HttpContext.Current.Session.SessionID);
if (IsValid)
{
// Validate the user password
var manager = new UserManager();
ApplicationUser user = manager.Find(UserName.Text, Password.Text);
if (user != null)
{
Session["New"] = user.UserName;
Session["SESSIONID"] = Guid.NewGuid();
String sessionID = HttpContext.Current.Session.SessionID;
System.Diagnostics.Debug.WriteLine("Session ID:" + sessionID);
System.Diagnostics.Debug.WriteLine("User GUID:" + Session["SESSIONID"]);
IdentityHelper.SignIn(manager, user, RememberMe.Checked);
//IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>());
var Test1 = roleManager.FindById(user.Id);
var Test2 = roleManager.FindByName(user.UserName);
//IdentityResult addRoles = manager.AddToRole(storedUser.Id, newRole);
//var Test3 = manager.GetRoles(user.UserName);
//var Test4 = manager.IsInRole(user.Id,"Administrator");
//var Test5 = manager.GetRoles(user.Id);
//var Test = HttpContext.Current.User.IsInRole("Administrator");
//Retrieve Role ID
try
{
//Retrieve from database
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand();
//SqlDataReader reader;
string queryString = "SELECT * FROM AspNetUserRoles where UserId='" + user.Id+"'";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, conn);
DataSet ds = new DataSet();
conn.Open();
adapter.Fill(ds);
conn.Close();
var Role_ID = ds.Tables[0].Rows[0][1].ToString();
string fetchRoleName = "SELECT * FROM AspNetRoles where Id='" + Role_ID + "'";
SqlDataAdapter fetchRoleNameadapter = new SqlDataAdapter(fetchRoleName, conn);
DataSet fetchRoleNameds = new DataSet();
conn.Open();
fetchRoleNameadapter.Fill(fetchRoleNameds);
conn.Close();
var Role_Name = fetchRoleNameds.Tables[0].Rows[0][1].ToString();
System.Diagnostics.Debug.WriteLine("Role_Name:" + Role_Name);
if(Role_Name == "Administrator")
{
Session["AdminFlag"] = "True";
}
else
{
Session["AdminFlag"] = null;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception:" + ex);
}
System.Diagnostics.Debug.WriteLine("Session Admin Flag:" + Session["AdminFlag"]);
Response.Redirect("../welcome.aspx");
}
else
{
FailureText.Text = "Invalid username or password.";
ErrorMessage.Visible = true;
}
}
}
示例15: AddRoleToUser
public ActionResult AddRoleToUser(string roleName, string userName)
{
List<string> roles;
using (var context = new ApplicationDbContext())
{
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
var user = userManager.FindByName(userName);
if (user == null)
{
throw new Exception("User not found!");
}
if (roleManager == null)
{
throw new Exception("Roles not found!");
}
var role = roleManager.FindByName(roleName);
if (userManager.IsInRole(user.Id, role.Name))
{
ViewBag.ErrorMessage = "This user already has the role specified!";
roles = (from r in roleManager.Roles select r.Name).ToList();
ViewBag.Roles = new SelectList(roles);
ViewBag.UserName = userName;
return View();
}
else
{
userManager.AddToRole(user.Id, role.Name);
context.SaveChanges();
List<string> userRoles;
var userRoleIds = (from r in user.Roles select r.RoleId);
userRoles = (from id in userRoleIds
let r = roleManager.FindById(id)
select r.Name).ToList();
ViewBag.UserName = userName;
ViewBag.RolesForUser = userRoles;
return View("ViewUserRoles");
}
}
}