在 MVC 中启用和创建角色

本文关键字:创建 角色 启用 MVC | 更新日期: 2023-09-27 17:56:41

如何在 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);
        }
    }

在 MVC 中启用和创建角色

第一个 web.config 添加以下内容

<system.web>
    <roleManager enabled="true" />
    ...

添加角色与 ASP.NET 相同

Roles.CreateRole("RoleName");
Roles.AddUserToRole("userName", "RoleName");

Web.config add

   <membership>
  <providers>
    <clear/>
    <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
  </providers>
</membership>
<profile>
  <providers>
    <clear/>
    <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
  </providers>
  <properties>
    <add name="insid" type="int" defaultValue="0"/>
  </properties>
</profile>
<roleManager enabled="true">
  <providers>
    <clear/>
    <add connectionStringName="ApplicationServices" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider"/>
    <add applicationName="/" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider"/>
  </providers>
</roleManager>
Roles.CreateRole("RoleName");
Roles.AddUserToRole("userName", "RoleName");