无法在asp.net身份中添加角色

时间:2018-05-05 13:44:16

标签: asp.net asp.net-mvc asp.net-identity

我使用以下代码添加用户的角色。

    Roles.AddUserToRole(model.Email, "COMPANYVIP");

然后我收到了这个错误:

    The Role Manager feature has not been enabled
经过一些研究后我发现我们必须在web.config中添加以下连接字符串

    <configuration>
      <system.web>
        <roleManager enabled="true" />
      </system.web>
    </configuration>

添加此消除了我的第一个错误,但现在我收到此错误:

    A network-related or instance-specific error occurred while establishing a connection to SQL Server
我现在该怎么办?

1 个答案:

答案 0 :(得分:1)

set_target_properties(libB PROPERTIES LINK_FLAGS "-Wl,-rpath,/path/to/libA/installation") web.config中移除您的更改,添加以下对Startup.Auth的引用:

ConfigureAuth

然后在您的Controller中,确保它在构造函数中包含它:

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的Dispose中(如果有的话):

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;
        }
    }
}

您可能还需要将此代码添加到protected override void Dispose(bool disposing) { if (disposing) { // include this if (_roleManager != null) { _roleManager.Dispose(); _roleManager = null; } } base.Dispose(disposing); } (如果您使用的是模板,则在App_Start文件夹中):

IdentityConfig

您现在应该可以在Controller中使用RoleManager。