我使用ASP.Net Identity创建一个基于角色身份验证的应用。我想创建一些自定义角色。当我这样做时,我得到以下异常。但我无法弄清楚这里有什么问题。由于我是新手,请帮帮我。提前致谢。
我得到了例外 var appRoleManager = new ApplicationRoleManager(new RoleStore(context.Get())); 它位于ApplicationRoleManager.cs类
中using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EasyMaintain.SecurityWebAPI
{
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
: base(roleStore)
{
}
//create instances for each request
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
var appRoleManager = new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<AuthContext>()));
return appRoleManager;
}
}
}
RoleModel.cs
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Routing;
namespace EasyMaintain.SecurityWebAPI.Models
{
public class RoleModel
{
private UrlHelper _UrlHelper;
private ApplicationUserManager _AppUserManager;
public RoleModel(HttpRequestMessage request, ApplicationUserManager appUserManager)
{
_UrlHelper = new UrlHelper(request);
_AppUserManager = appUserManager;
}
public RoleReturnModel Create(IdentityRole appRole)
{
return new RoleReturnModel
{
Url = _UrlHelper.Link("GetRoleById", new { id = appRole.Id }),
Id = appRole.Id,
Name = appRole.Name
};
}
}
public class RoleReturnModel
{
public string Url { get; set; }
public string Id { get; set; }
public string Name { get; set; }
}
}
RoleController.cs
using EasyMaintain.SecurityWebAPI.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using static EasyMaintain.SecurityWebAPI.Models.RoleBindingModels;
namespace EasyMaintain.SecurityWebAPI.Controllers
{
[Authorize(Roles = "SuperAdmin")]
[RoutePrefix("api/roles")]
public class RolesController : BaseApiController
{
// GET api/roles
[Route("{id:guid}", Name = "GetRoleById")]
public async Task<IHttpActionResult> GetRole(string Id)
{
var role = await this.AppRoleManager.FindByIdAsync(Id);
if (role != null)
{
return Ok(TheModelFactory.Create(role));
}
return NotFound();
}
//GET api/roles/5
[Route("", Name = "GetAllRoles")]
public IHttpActionResult GetAllRoles()
{
var roles = this.AppRoleManager.Roles;
return Ok(roles);
}
// POST api/roles
[Route("create")]
[HttpPost]
public async Task<IHttpActionResult> Create(RoleBindingModels model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var role = new IdentityRole { Name = model.Name };
var result = await this.AppRoleManager.CreateAsync(role);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
Uri locationHeader = new Uri(Url.Link("GetRoleById", new { id = role.Id }));
return Created(locationHeader, TheModelFactory.Create(role));
}
[Route("{id:guid}")]
public async Task<IHttpActionResult> DeleteRole(string Id)
{
var role = await this.AppRoleManager.FindByIdAsync(Id);
if (role != null)
{
IdentityResult result = await this.AppRoleManager.DeleteAsync(role);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
return NotFound();
}
[Route("ManageUsersInRole")]
public async Task<IHttpActionResult> ManageUsersInRole(UsersInRoleModel model)
{
var role = await this.AppRoleManager.FindByIdAsync(model.Id);
if (role == null)
{
ModelState.AddModelError("", "Role does not exist");
return BadRequest(ModelState);
}
foreach (string user in model.EnrolledUsers)
{
var appUser = await this.AppUserManager.FindByIdAsync(user);
if (appUser == null)
{
ModelState.AddModelError("", String.Format("User: {0} does not exists", user));
continue;
}
if (!this.AppUserManager.IsInRole(user, role.Name))
{
IdentityResult result = await this.AppUserManager.AddToRoleAsync(user, role.Name);
if (!result.Succeeded)
{
ModelState.AddModelError("", String.Format("User: {0} could not be added to role", user));
}
}
}
foreach (string user in model.RemovedUsers)
{
var appUser = await this.AppUserManager.FindByIdAsync(user);
if (appUser == null)
{
ModelState.AddModelError("", String.Format("User: {0} does not exists", user));
continue;
}
IdentityResult result = await this.AppUserManager.RemoveFromRoleAsync(user, role.Name);
if (!result.Succeeded)
{
ModelState.AddModelError("", String.Format("User: {0} could not be removed from role", user));
}
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
return Ok();
}
}
}
答案 0 :(得分:1)
检查在Startup.Auth中,RoleManager的引用方式如下:
public void ConfigureAuth(IAppBuilder app)
{
// Add this reference
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
}
确保您的Controller包含此构造函数:
private ApplicationRoleManager _roleManager;
public ApplicationRoleManager RoleManager { get { return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); } private set { _roleManager = value; } }
并确保在控制器中丢弃角色管理器,如下所示:
protected override void Dispose(bool disposing)
{
if (disposing && RoleManager != null)
{
RoleManager.Dispose();
RoleManager = null;
}
if (disposing)
{
context.Dispose();
}
base.Dispose(disposing);
}