2016-10-24 19 views
0

私はASP.Net Identityを使用して、ロールベースの認証でアプリケーションを作成しています。カスタムロールをいくつか作成したいと思います。私がそれをするとき、私は次の例外を得る。しかし、私はここで何が間違っているのか理解できません。私はこれを初めて知ったので、私を助けてください。前もって感謝します。Microsoft.AspNet.Identity.EntityFramework.dllで 'System.ArgumentNullException'タイプの例外が発生しました

例外が発生する var appRoleManager = new ApplicationRoleManager(新しいRoleStore(context.Get())); ApplicationRoleManager.csクラスでStartup.Authで、RoleManagerが同様に参照されていること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(); 
      } 
    } 
} 

答えて

1

チェック

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; 
     } 
    } 
} 

ある これは:

public void ConfigureAuth(IAppBuilder app) 
{ 
    // Add this reference 
    app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); 
} 

あなたのコントローラは、このコンストラクタが含まれていることを確認してください:

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); 
} 
関連する問題