简体   繁体   English

Microsoft.AspNet.Identity.EntityFramework.dll中发生类型为“ System.ArgumentNullException”的异常

[英]An exception of type 'System.ArgumentNullException' occurred in Microsoft.AspNet.Identity.EntityFramework.dll

I am using ASP.Net Identity to create an app with roles based authentication. 我正在使用ASP.Net Identity创建具有基于角色的身份验证的应用程序。 I want to create some custom roles. 我想创建一些自定义角色。 When I do that I get the following exception. 当我这样做时,我得到以下异常。 But I'm unable to figure what's wrong here. 但我无法弄清楚这里出了什么问题。 Since I'm new to this Please do help me out. 由于我是新手,请帮助我。 Thanks in advance. 提前致谢。

I get the exception in var appRoleManager = new ApplicationRoleManager(new RoleStore(context.Get())); 我在var appRoleManager = new ApplicationRoleManager(new RoleStore(context.Get()))中得到了异常; which is in the ApplicationRoleManager.cs class 在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;
        }
    }
}

The RoleModel.cs 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; }
    }

}

The RoleController.cs 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();
            }
    }
}

Check that in Startup.Auth, the RoleManager is referenced like this: 检查在Startup.Auth中是否像这样引用了RoleManager:

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

Make sure your Controller includes this constructor: 确保您的Controller包含以下构造函数:

private ApplicationRoleManager _roleManager;
public ApplicationRoleManager RoleManager { get { return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); } private set { _roleManager = value; } }

And make sure you dispose of the Role Manager in your Controller like this: 并确保您像这样在控制器中处置角色管理器:

protected override void Dispose(bool disposing)
{
    if (disposing && RoleManager != null)
    {
        RoleManager.Dispose();
        RoleManager = null;
    }
    if (disposing)
    {
        context.Dispose();
    }
    base.Dispose(disposing);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Microsoft.Xna.Framework.Graphics.dll中发生了类型为&#39;System.ArgumentNullException&#39;的未处理异常 - An unhandled exception of type 'System.ArgumentNullException' occurred in Microsoft.Xna.Framework.Graphics.dll mscorlib.dll中发生类型&#39;System.ArgumentNullException&#39;的异常,但未在用户代码中处理 - An exception of type 'System.ArgumentNullException' occurred in mscorlib.dll but was not handled in user code mscorlib.dll中发生了类型为&#39;System.ArgumentNullException&#39;的未处理异常附加信息:路径不能为null - An unhandled exception of type 'System.ArgumentNullException' occurred in mscorlib.dll Additional information: Path cannot be null System.Xml.Linq.dll中发生类型为&#39;System.ArgumentNullException&#39;的未处理异常附加信息:值不能为null - An unhandled exception of type 'System.ArgumentNullException' occurred in System.Xml.Linq.dll Additional information: Value cannot be null 抛出异常:mscorlib.ni.dll 中的“System.ArgumentNullException” - Exception thrown: 'System.ArgumentNullException' in mscorlib.ni.dll EntityFramework dll中发生了&#39;System.StackOverflowException&#39;类型的未处理异常 - An unhandled exception of type 'System.StackOverflowException' occurred in EntityFramework dll EntityFramework.dll中出现未处理的“System.TypeInitializationException”类型异常 - An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll EntityFramework.dll中发生了&#39;System.StackOverflowException&#39;类型的未处理异常 - An unhandled exception of type 'System.StackOverflowException' occurred in EntityFramework.dll Moq模拟引发了类型为&#39;System.ArgumentNullException&#39;的异常 - Moq mock threw an exception of type 'System.ArgumentNullException' 使用 Linq 和 DataSet 在 System.Data.DataSetExtensions.dll 中发生“System.ArgumentNullException” - 'System.ArgumentNullException' occurred in System.Data.DataSetExtensions.dll using Linq and DataSet
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM