【问题标题】:How to add roles to users in ASP.NET with OWIN如何使用 OWIN 在 ASP.NET 中为用户添加角色
【发布时间】:2015-08-23 05:30:46
【问题描述】:

我是 ASP.NET 的新手,我正在制作一个简单的项目来练习。我从一个没有身份验证的简单 MVC 项目开始,因为它添加了许多我不理解的代码。

但现在我想在我的系统中添加一个成员,所以我遵循了这个指南:

http://benfoster.io/blog/aspnet-identity-stripped-bare-mvc-part-1

http://benfoster.io/blog/aspnet-identity-stripped-bare-mvc-part-2

但我不知道在哪里可以向用户实体添加角色..

我的 Startup 课程是这样的:

public class Startup
    {
        public static Func<UserManager<Usuario>> UserManagerFactory { get; private set; }
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "ApplicationCookie"
            });
            UserManagerFactory = () =>
                {
                    var usermanager = new UserManager<Usuario>(new UserStore<Usuario>(new Vetpet3Context()));
                    usermanager.UserValidator = new UserValidator<Usuario>(usermanager)
                    {
                        AllowOnlyAlphanumericUserNames = false
                    };
                    return usermanager;
                };
        }
    }

我正在(目前)使用此操作创建我的用户:

[HttpPost]
        public async Task<ActionResult> Register(RegisterModel model)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            var user = new Usuario
            {
                UserName=model.correo,
                correo = model.correo
            };
            var result = await userManager.CreateAsync(user, model.password);
            if (result.Succeeded)
            {
                await SignIn(user);
                return RedirectToAction("index", "Home");
            }
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error);
            }

            return View();
        }

所以此时一切正常,但我需要为用户添加不同的角色,这就是问题,我如何实现这部分?我读过很多指南,但每个人做的事情都不一样,我不知道如何为我的新用户添加角色以及如何在他们登录时声明这些角色

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    成功注册后为用户添加角色:

    if (result.Succeeded)
                {
                    var roleResult = userManager.AddToRole(user.Id, "Admin");
                    await SignIn(user);
                    return RedirectToAction("index", "Home");
                }
    

    检查用户是否在角色中:

    userManager.IsInRole(user.Id, "Admin");
    

    在任何 ASP.NET MVC [授权] 控制器中甚至更简单:

    User.IsInRole("roleName");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多