问题描述
我一直努力让自己对ASP.Net Core Identity有所了解,尽管取得了一些成功,但我遇到了无法解决的问题。
我已经在测试应用程序中创建了一个角色管理页面,该页面列出了当前的站点角色,并具有一个供用户创建新角色的文本框。该页面加载正常,并且我为应用程序播种了1个角色,并为用户显示了内容,但是创建新角色的表单在我尝试运行的任何Async方法上均崩溃。
这是我的Startup.cs配置。我希望这段代码不会有任何问题,因为我已经在互联网上看到了这一切。
services.AddDbContext<ApplicationDbContext>(options =>
options.UsesqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<IdentityUser,IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
这是我在Page模型中初始化 roleManager 的方式。
private RoleManager<IdentityRole> roleManager;
public RolesModel(RoleManager<IdentityRole> roleManager)
{
this.roleManager = roleManager;
}
这是我的OnPost方法,用于添加新角色。我已经编写并重写了此代码,以便首先尝试 RoleExistsAsync 或 CreateAsync ,但是两者都会导致调试器停止处理并直接进入页面渲染,其中 Model 未设置为对象的实例,并且页面出错。我不确定为什么 catch 部分也无法捕获错误。
public async void OnPost()
{
try
{
if (ModelState.IsValid)
{
// creates new role from form data
IdentityRole role = new IdentityRole(HttpContext.Request.Form["NewRole"]);
var exists = await roleManager.RoleExistsAsync(HttpContext.Request.Form["NewRole"]);
if (!exists)
{
var results = await roleManager.CreateAsync(role);
if (results.Succeeded)
{
Message = "Success! Role created.";
// binds list of roles
BindRoles();
}
}
}
}
catch (Exception ex)
{
Error = ex.Message;
}
}
有什么建议吗?
更新:我添加了以下HTML表单,该表单正在尝试发布...
<form method="post">
<table class="table table-responsive">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>normalized Name</th>
<th>Concurrency Stamp</th>
</tr>
</thead>
<tbody>
@if (Model.roles != null)
{
@if (Model.roles.Count > 0)
{
@foreach (var r in Model.roles)
{
<tr>
<td>@r.Id</td>
<td>@r.Name</td>
<td>@r.normalizedname</td>
<td>@r.ConcurrencyStamp</td>
</tr>
}
}
else
{
<tr>
<td colspan="4">
<em>No roles</em>
</td>
</tr>
}
}
</tbody>
<tfoot>
<tr>
<td colspan="4">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="New Role" aria-label="New Role" id="NewRole" name="NewRole">
<div class="input-group-append">
<button type="submit" formmethod="post" class="btn btn-primary" href="#" rel="button">Add Role</button>
</div>
</div>
</td>
</tr>
</tfoot>
</table>
</form>
解决方法
更新我的OnPost
方法以返回Task<IActionResult>
似乎已经解决了我的问题。
public async Task<IActionResult> OnPost()
感谢评论部分的帮助。