删除您在web.config 和Startup.Auth 中的更改,将以下引用添加到ConfigureAuth:
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(ApplicationDbContext.Create);
// Add this reference to RoleManager (without changing any other items)
// Make sure it is added below ApplicationDbContext.Create
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
}
然后在你的 Controller 中,确保它在构造函数中包含这个:
public class YourController : Controller
{
// Add this
private ApplicationRoleManager _roleManager;
// Add roleManager
public YourController(ApplicationRoleManager roleManager)
{
// Add this
RoleManager = roleManager;
}
public ApplicationRoleManager RoleManager {
get {
return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
private set {
_roleManager = value;
}
}
}
并将其包含在控制器的 Dispose 中(如果有的话):
protected override void Dispose(bool disposing)
{
if (disposing)
{
// include this
if (_roleManager != null)
{
_roleManager.Dispose();
_roleManager = null;
}
}
base.Dispose(disposing);
}
您可能还需要将此代码添加到IdentityConfig(如果您使用模板,则在 App_Start 文件夹中):
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
: base(roleStore)
{ }
public static ApplicationRoleManager Create(
IdentityFactoryOptions<ApplicationRoleManager> options,
IOwinContext context)
{
var manager = new ApplicationRoleManager(
new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
return manager;
}
}
您现在应该可以在 Controller 中使用 RoleManager。