我正在尝试使用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); 可以在attached snapshot中找到applicationRole对象变量的Quick监视值。当执行上述行时,控件转到ApplicationDbContext类并执行BuildModel()方法。我还没有对AspNetRoles表做任何更改,但是应用程序仍然指示我运行迁移脚本,任何人都可以帮我解决这个问题吗?如何动态地将角色/声明添加到Asp.net5 / EntityFramework7中的Asp.Net身份表?
注意:在运行时期间的RoleManager对象中,我看到错误消息为"值不能为空。\ r \ n参数名称:entityType",请找attached snapshot
答案 0 :(得分:1)
我找到了解决这个问题的方法。我还需要在ApplicationDbContext类中添加ApplicationRole。这解决了这个问题。
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
{
...
...
}
我从帖子How do I extend IdentityRole using Web API 2 + AspNet Identity 2
获得了解决方案