[英]unable to add roles in asp.net identity
I was using the following code to add roles of the user. 我正在使用以下代码添加用户角色。
Roles.AddUserToRole(model.Email, "COMPANYVIP");
and then i got this error: 然后我得到这个错误:
The Role Manager feature has not been enabled
after some research i found out that we have to add the following connection string in web.config 经过研究后,我发现我们必须在web.config中添加以下连接字符串
<configuration>
<system.web>
<roleManager enabled="true" />
</system.web>
</configuration>
adding this eliminated my first error but now i get this error: 添加这个消除了我的第一个错误,但是现在我得到了这个错误:
A network-related or instance-specific error occurred while establishing a connection to SQL Server
what should i do now? 我现在应该怎么办?
Remove your change in web.config
and in Startup.Auth
add the following reference to ConfigureAuth
: 删除
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);
}
Then in your Controller, make sure it includes this in the constructor: 然后在您的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;
}
}
}
and also include this in the Controller's Dispose (if you have it): 并将其包含在Controller的Dispose中(如果有):
protected override void Dispose(bool disposing)
{
if (disposing)
{
// include this
if (_roleManager != null)
{
_roleManager.Dispose();
_roleManager = null;
}
}
base.Dispose(disposing);
}
You may also need to add this code to IdentityConfig
(in the App_Start folder if you're using the template): 您可能还需要将此代码添加到
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;
}
}
You should now be able to use the RoleManager in the Controller. 您现在应该可以在Controller中使用RoleManager。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.