0

我正在尝试使用 Asp.Net5/EntityFramework7 中的 Asp.Net Identity 创建 WebAPI 服务以提供安全性。我使用 Asp.Net 5 模板创建了一个 Web 应用程序项目。它为我提供了用于管理用户的模板代码。现在我正在尝试对角色/声明做同样的事情。

我创建了一个继承 IdentityRole 的 ApplicationRole 类。

 public class ApplicationRole: IdentityRole
    {
        public ApplicationRole() : base() { }
        public ApplicationRole(string name, string description) : base(name)
        {
            this.Description = description;
        }
        public virtual string Description { get; set; }
    }

我添加新角色的 Web API 控制器类方法如下:

 [HttpPost("CreateRole", Name = "CreateRole")]
        public async Task CreateRole([FromBody]string role)
        {
            var applicationRole = new ApplicationRole(role, role);
            var idResult = await _roleManager.CreateAsync(applicationRole);
            if (idResult.Succeeded)
            {
                _logger.LogInformation(3, "Role Created successfully");
            }
            else
            {
                var resp = new HttpResponseMessage()
                {
                    Content = new StringContent("Internal error occurred"),
                    ReasonPhrase = "Internal error occurred",
                    StatusCode = HttpStatusCode.BadRequest
                };
                throw new HttpResponseException(resp);
            }
        }

当我尝试执行此代码时,应用程序崩溃并出现异常

 "A database operation failed while processing the request.
        ArgumentNullException: Value cannot be null.
         Parameter name: entityType 
        There are pending model changes for ApplicationDbContext
        Scaffold a new migration for these changes and apply them to the database from the command line:

        > dnx ef migrations add [migration name] 
        > dnx ef database update
    "

它在 var idResult = await _roleManager.CreateAsync(applicationRole); 行中崩溃 可以在附加的快照中找到 applicationRole 对象变量的 Quick watch 值。执行上述行时,控件转到 ApplicationDbContext 类并执行 BuildModel() 方法。我没有对 AspNetRoles 表进行任何更改,但应用程序仍然指向我运行迁移脚本,有人可以帮我解决这个问题吗?如何将角色/声明动态添加到 Asp.net5/EntityFramework7 中的 Asp.Net 身份表?

注意:在运行时的 RoleManager 对象中,我看到错误消息为“值不能为空。\r\n参数名称:实体类型”,请查找附加快照

4

1 回答 1

1

我找到了解决这个问题的方法。我还需要在 ApplicationDbContext 类中添加 ApplicationRole。这解决了问题。

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
    {
...
...
}

我从帖子中得到了解决方案How do I extend IdentityRole using Web API 2 + AspNet Identity 2

于 2016-06-04T03:44:04.850 回答