在mvc中启用和创建角色

Nee*_*eel -2 c# authentication model-view-controller asp.net-mvc authorization

如何在mvc中启用角色?我的代码在下面给出,我不知道如何创建角色,我想将其添加到数据库..

[AttributeUsage(AttributeTargets.All)]
    public class UserRightAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //write your user right logic
            //if user has right to do nothig otherwise redirect to error page.
            string message = "It seems You  are not authorize to view this part of the web site!!!.";
            RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
            redirectTargetDictionary.Add("area", "");
            redirectTargetDictionary.Add("action", "SaveData");
            redirectTargetDictionary.Add("controller", "Home");
            redirectTargetDictionary.Add("customMessage", message);
            filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
        }
    }
Run Code Online (Sandbox Code Playgroud)

Ali*_*hşi 6

首先是web.config添加以下内容

<system.web>
    <roleManager enabled="true" />
    ...
Run Code Online (Sandbox Code Playgroud)

例如,添加角色与ASP.NET相同

Roles.CreateRole("RoleName");
Roles.AddUserToRole("userName", "RoleName");
Run Code Online (Sandbox Code Playgroud)