Asp.net WebForms Enable Roles

2019-08-22 05:33发布

问题:

I've created a Webpage via Visual Studio 2017 using ASP.NET WebForms.

I'm using the build-in User Management and created some users.

Now I want to use the Role-Function.

First I've enabled the roleManager, but then I get a new error "Could not find stored procedure 'dbo.aspnet_CheckSchemaVersion"

I've tried to use the aspnet_regsql.exe to add the necessary parts to the database, but now I have two kind of tables in my database: AspNetUsers and aspnet_Users.

What Do I have to do, to enable roles with the old AspNet-Schematic?

回答1:

You got to configure the default role provider/membership provider in web.config and run aspnet_regsql.exe against your database.

here is the documentations: https://docs.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-security/membership/creating-the-membership-schema-in-sql-server-cs

  <system.web>
    <roleManager enabled="true" cacheRolesInCookie="false" defaultProvider="AspNetSqlRoleProvider">
      <providers>
        <clear />
        <add applicationName="app-name" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="roleManagerSqlConnString" />
        <add applicationName="app-name" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" />
      </providers>
    </roleManager>
  </system.web> 
using System.Web.Security;

                string userName = HttpContext.Current.User.Identity.Name;
                if (!Roles.IsUserInRole(roleName))
                {
                    Roles.AddUserToRole(userName, roleName);
                }


回答2:

Standard-WebForms created with VisualStudio using Microsoft.AspNet.Identity so also the Database is created to use the Schematic of Microsoft.AspNet.Identity.

Therefore you have to use the RoleManager to add Roles:

string roleName = "role";
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

if (!roleManager.RoleExists(roleName))
{
    var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
    role.Name = TextBoxRole.Text;
    roleManager.Create(roleName);
}

System.Web.Security has it's own Schematic and does not work with Microsoft.AspNet.Identity