저는 Identity 2.0 멤버십을 구현했으며 지금 후회하기 시작했습니다. 그러나 나는이 프로젝트에서 너무 깊어서 돌이킬 수 없다. 내 문제는 아마 대부분 간단하므로 희망을 갖고 도움을 얻을 수 있습니다.MVC Identity 2.0 및 역할 관리
MVC5 응용 프로그램에 그리드 컨트롤이 있습니다.
VIEW
public class PTSUsersViewModel
{
public string _ID { get; set; }
public string _email { get; set; }
public int? _employeeID { get; set; }
public string _phoneNumber { get; set; }
public string _role { get; set; }
}
내 목표는 단지 이메일, 직원 ID 및 PHONENUMBER처럼 Grid.Column을을 사용하여 등록 된 각 사용자의 역할을 표시하는 것입니다
@using System.Web.Helpers;
@model List<PTSPortal.Models.PTSUsersViewModel>
@{
var grid = new WebGrid(source: Model, defaultSort: "PropertyName", rowsPerPage: 10);
}
<div id="ContainerBox">
@grid.GetHtml(columns: grid.Columns(
grid.Column("_email", "Email", canSort: true, style: "text-align-center"),
grid.Column("_employeeID", "EmployeeID", canSort: true, style: "text-align-center"),
grid.Column("_phoneNumber", "Phone", canSort: true, style: "text-align-center")
//-----I want to display the user's role here!------
))
</div>
뷰 모델. 내 using 문 내에서
CONTROLLER
public ActionResult PTSUsers()
{
List<PTSUsersViewModel> viewModel = FetchInfo().ToList();
return View(viewModel);
}
private static IEnumerable<PTSUsersViewModel> FetchInfo()
{
PTSPortalEntities context = new PTSPortalEntities();
using (ApplicationDbContext _context = new ApplicationDbContext())
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_context));
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
}
return (from a in context.AspNetUsers
orderby a.Email ascending
select new PTSUsersViewModel
{
_ID = a.Id,
_email = a.Email,
_employeeID = a.EmployeeID,
_phoneNumber = a.PhoneNumber,
//_role = ........
}).ToList<PTSUsersViewModel>();
}
, 나는 var에으로 roleManager 및 var에 userManager을 가지고 있지만 그들은 아무것도하지 않습니다. 나는 사용자의 역할을 검색하려고 시도했지만, 그 때 내가 멈추었을 때 SOF에 몇 가지 팁이나 더 나은 접근 방법을 제시 할 것이라고 생각했습니다.
이제 메모를합니다. 프로젝트에서 이미 생성 된 일부 서비스 메소드가 다른 컨트롤러 메소드 내에서 훌륭하게 작동합니다. 아마도 위의 내 문제에서 이러한 내용을 사용하거나 수정할 수 있습니다.
public class AppServices
{
// Roles used by this application
public const string AdminRole = "Admin";
public const string TrainerRole = "Trainer";
private static void AddRoles(ref bool DataWasAdded)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (roleManager.RoleExists(AdminRole) == false)
{
Guid guid = Guid.NewGuid();
roleManager.Create(new IdentityRole() { Id = guid.ToString(), Name = AdminRole });
DataWasAdded = true;
}
if (roleManager.RoleExists(TrainerRole) == false)
{
Guid guid = Guid.NewGuid();
roleManager.Create(new IdentityRole() { Id = guid.ToString(), Name = TrainerRole });
DataWasAdded = true;
}
}
/// <summary>
/// Checks if a current user is in a specific role.
/// </summary>
/// <param name="role"></param>
/// <returns></returns>
public static bool IsCurrentUserInRole(string role)
{
if (role != null)
{
using (ApplicationDbContext _context = new ApplicationDbContext())
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_context));
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
if (UserManager.IsInRole(GetCurrentUserID(), role))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Adds a user to a role
/// </summary>
/// <param name="userId"></param>
/// <param name="RoleToPlaceThemIn"></param>
public static void AddUserToRole(string userId, string RoleToPlaceThemIn)
{
// Does it need to be added to the role?
if (RoleToPlaceThemIn != null)
{
using (ApplicationDbContext _context = new ApplicationDbContext())
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_context));
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
if (UserManager.IsInRole(userId, RoleToPlaceThemIn) == false)
{
UserManager.AddToRole(userId, RoleToPlaceThemIn);
}
}
}
}
어떤 조언을 주시면 감사하겠습니다.
읽기 [이] (http://stackoverflow.com/questions/6263927/role-management-in-mvc3) 연결된 문제가 발생했습니다 2011 년부터입니다 – VeNoMiS
@VeNoMiS 도움이 될 수 당시 Identity 프레임 워크는 없었습니다. – trailmax
그건 그렇고, 조쉬, 당신의 구현은'IsCurrentUserInRole' 과도한입니다. 당신은'ClaimsPrincipal.Current.IsInRole ("rolename")을 호출 할 수 있으며, 데이터베이스 호출이 없으면 똑같이 수행됩니다. – trailmax