【发布时间】:2026-02-14 22:50:01
【问题描述】:
我正在开发一个 MVC 应用程序,并且我有一个创建角色的表单。表单中的数据被正确发送到创建后操作方法。这个方法的签名是:
[HttpPost]
public async Task<ActionResult> Create([Bind(Include = "Name")] AppRole appRole, string [] PrivsChecked)
基本上,这是为了创建一个角色,并附加为该角色选择的权限,就像在表单上选择的用户一样。问题在于,在为角色分配权限时,找不到新创建的角色。部分代码如下:
public async Task<ActionResult> Create([Bind(Include = "Name")] AppRole appRole, string [] PrivsChecked)
{
if (PrivsChecked == null || PrivsChecked.Length == 0)
{
return Json(new { status = "error", message = "At least one privilege must be selected." });
}
else
{
if (ModelState.IsValid)
{
IdentityResult result
= await RoleManager.CreateAsync(new AppRole(appRole.Name));
if (result.Succeeded)
{
var approleToUpdate = db.IdentityRoles.Where(i => i.Id == appRole.Id).FirstOrDefault();
.
.
.
appRoleToUpdate 被分配为 null,但至少达到了该代码,这意味着角色创建成功。在控制器中声明为全局变量private AppIdentityDbContext db = new AppIdentityDbContext();的db上下文如下:
using IdentityDevelopment.Models;
using Microsoft.AspNet.Identity;
namespace IdentityDevelopment.Infrastructure
{
public class AppIdentityDbContext : IdentityDbContext<AppUser>
{
public AppIdentityDbContext() : base("IdentityDb") { }
static AppIdentityDbContext()
{
Database.SetInitializer<AppIdentityDbContext>(new IdentityDbInit());
}
public static AppIdentityDbContext Create()
{
return new AppIdentityDbContext();
}
public System.Data.Entity.DbSet<IdentityDevelopment.Models.AppRole> IdentityRoles { get; set; }
public System.Data.Entity.DbSet<IdentityDevelopment.Models.AppPrivilege> AppPrivileges { get; set; }
}
public class IdentityDbInit : NullDatabaseInitializer<AppIdentityDbContext>
{
}
}
奇怪的是,Edit 方法中也存在非常相似的代码,在这种情况下,找到了appRoleToUpdate。我该怎么做才能在同一方法中找到新创建的角色?这与方法的异步性质有什么关系吗?
谢谢。
【问题讨论】:
标签: c# asp.net-mvc entity-framework asp.net-identity