【问题标题】:An exception of type 'System.ArgumentNullException' occurred in Microsoft.AspNet.Identity.EntityFramework.dllMicrosoft.AspNet.Identity.EntityFramework.dll 中出现“System.ArgumentNullException”类型的异常
【发布时间】:2016-10-24 12:18:31
【问题描述】:

我正在使用 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();
            }
    }
}

【问题讨论】:

    标签: c# asp.net asp.net-identity-2


    【解决方案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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-20
      • 2015-11-26
      • 2015-09-27
      • 2021-09-22
      • 2015-06-25
      • 2013-12-01
      • 2017-09-05
      相关资源
      最近更新 更多