首页 > 解决方案 > 如何在 ASP.NET 身份框架中从用户中删除所有角色

问题描述

我正在尝试使用下面的代码,但得到参数“manager”为空的异常。我该如何解决?

private ApplicationUserManager _userManager;

    [HttpDelete]
    public async Task DeleteUserRoles()
    {
        var userId = "ec6ea171-70f5-4fd9-93f2-5a05a2f88e3b";

        await _userManager.RemoveFromRolesAsync(userId, _userManager.GetRoles(userId).ToArray());

    }

标签: asp.netasp.net-identity

解决方案


有效的代码。

using Microsoft.AspNet.Identity;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity.Owin;

.......
 private ApplicationUserManager _userManager; 

        public UsersController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
        {
            UserManager = userManager;

        }
        public ApplicationUserManager UserManager
        {
            get
            {
               return _userManager ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }
 [HttpDelete]
        public async Task DeleteUserRoles()
        {
            var userId = "ec6ea171-70f5-4fd9-93f2-5a05a2f88e3b";
            await UserManager.RemoveFromRolesAsync(userId, UserManager.GetRoles(userId).ToArray());
        }

推荐阅读