首页 文章

如何在ASP.NET 4.5 MVC应用程序上为用户分配角色

提问于
浏览
-1

我使用ASP.NET 4.5模板创建了MVC Web应用程序 . 在Web.config中,我将SQL连接字符串更改为指向现有的SQL Server数据库 .

我运行该项目并在我的SQL Server数据库中创建了必要的表 . 我还创建了一个新用户 .

我的第一个问题是如何创建 user role ?我的第二个问题是如何使用“角色”来授予我的用户尊重的权限,以便只访问我的应用程序的某些部分?

亲切的问候,

enter image description here

enter image description here

enter image description here

1 回答

  • 0

    Ok. Here is how to created roles.

    我正在使用VS2015和ASP.NET 4.5 MVC . 我使用 Microsoft Asp.Net 4.5 identity 进行身份验证 .

    context.Roles.Add(new icrosoft.AspNet.Identity.EntityFramework.IdentityRole()

    所以在我的模型_2965708中:

    // POST: /Roles/Create
    [HttpPost]
    public ActionResult Create(FormCollection collection)
    {
        try
        {
            context.Roles.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole()
            {
                Name = collection["RoleName"]
            });
            context.SaveChanges();
            ViewBag.ResultMessage = "Role created successfully !";
            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }
    

    我还分别在我的每个控制器下面放置代码:

    [Authorize(Roles = "TestRole")]
    

相关问题