C# Identity 2.0中的ASp.net角色管理

C# Identity 2.0中的ASp.net角色管理,c#,asp.net,.net,C#,Asp.net,.net,我有一个使用ASp.net Identity 2身份验证的网站项目。 我可以登录到该网站,注册新用户,运行迄今为止构建的应用程序页面。 但我需要添加角色管理,这样我就可以按用户限制功能。 事实证明,要想靠自己去学习它是非常困难的。 我的Asp.NET4.5书(Murach的Asp.NET4.5WebProgrammingwithC#2012)说“使用网站管理工具” 你可能已经知道了,MS已经淘汰了。 无论如何,我找到的几种方法都以惨败告终 所以,我开始为这个建立我自己的管理页面。 到目前为止,它

我有一个使用ASp.net Identity 2身份验证的网站项目。 我可以登录到该网站,注册新用户,运行迄今为止构建的应用程序页面。 但我需要添加角色管理,这样我就可以按用户限制功能。 事实证明,要想靠自己去学习它是非常困难的。 我的Asp.NET4.5书(Murach的Asp.NET4.5WebProgrammingwithC#2012)说“使用网站管理工具” 你可能已经知道了,MS已经淘汰了。 无论如何,我找到的几种方法都以惨败告终

所以,我开始为这个建立我自己的管理页面。 到目前为止,它是简单的,丑陋的,而且它的一部分仍然不起作用。我只是不知道为什么

这里附上了我的整个Web.config(为安全起见进行了编辑),以及添加角色的相关代码。到目前为止,测试代码将添加一个角色,然后尝试将其分配给我的用户ID

这个角色似乎被创造出来了,但我不知道在哪里。。。它不会在我的数据库的[dbo].[AspNetRoles]表中结束。我说似乎是,因为当我再试一次时,检查这个角色是否存在的测试就会跳出来,说它已经存在了。 如果(!Roles.RoleExists(newRoleName)) { Roles.CreateRole(newRoleName); }//结束创建新角色 项目数据文件夹中没有数据库

System.Web.Providers。显然是新的,标准类和 “这些通用提供者很可能是下一版本ASP.NET的默认提供者。”我听说。 我已分配正确的DB连接字符串。 很明显,仍然缺少一些东西,我继承了一些我不知道要寻找的默认值,在某个地方

任何提示或提示,不胜感激。 甚至是后来的一本书

Web.config

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <!--<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Parts-20160425083953.mdf;Initial Catalog=aspnet-Parts-20160425083953;Integrated Security=True" providerName="System.Data.SqlClient" />-->
    <add name="PartsDatabase" connectionString="Data Source=-redacted-;Initial Catalog=-mydatabasename-;User ID=--dbuserID--;Password=--thepassword--" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="emailServiceUserName" value="--emailuserid--" />
    <add key="emailServicePassword" value="--emailPW--" />
  </appSettings>
  <system.web>
    <!--<authentication mode="None" />-->
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="60" protection="All" slidingExpiration="true">
      </forms>
    </authentication>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
        <add namespace="Microsoft.AspNet.Identity" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      </controls>
    </pages>
    <membership defaultProvider="ASPNetMembershipProvider">
      <providers>
        <clear />
        <!--<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />-->
        <add name="ASPNetMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="PartsDatabase" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <profile defaultProvider="ASPNetProfileProvider">
      <providers>
        <clear />
        <!--<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />-->
        <add name="ASPNetProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="PartsDatabase" applicationName="/" />
      </providers>
    </profile>
    <roleManager defaultProvider="ASPNetRoleProvider" enabled="true">
      <providers>
        <clear />
        <!--<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />-->
        <add name="ASPNetRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="PartsDatabase" applicationName="/" />
      </providers>
    </roleManager>
    <sessionState mode="InProc" customProvider="ASPNetSessionProvider">
      <providers>
        <!--<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />-->
        <add name="ASPNetSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="PartsDatabase" />
      </providers>
    </sessionState>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

代码隐藏

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Owin;
using Sperry_Parts.Models;

namespace Parts.Account
{
    public partial class ManageUsers : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();

            gvUsers.DataSource = manager.Users.ToList();
            gvUsers.DataBind();
        }

-- Code-behind for the Add Role button --
        protected void btnAddRole_Click(object sender, EventArgs e)
        {
            string newRoleName = txtRole.Text.Trim();
            if (!Roles.RoleExists(newRoleName)) 
            {
                Roles.CreateRole(newRoleName); // This works once per new Role - where it Goes is anyone's guess
            } // End create new role


            // Check Users in Roles
            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var user = manager.FindByName("myusername");
            string username = user.UserName; // properly returns "myusername"
            if (Membership.GetUser("myusername") != null) // Fails - returns Null
                if (!Roles.IsUserInRole(user.UserName, newRoleName)) // Without the above check, this returns False, I'm not in this role... (natch)
                    Roles.AddUserToRole(user.UserName, newRoleName); // This fails, can't find the user

        } // End Add Role
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Web;
使用System.Web.UI;
使用System.Web.UI.WebControl;
使用System.Web.Security;
使用Microsoft.AspNet.Identity;
使用Microsoft.AspNet.Identity.Owin;
使用Owin;
使用Sperry_零件模型;
名称空间部分.Account
{
公共部分类ManageUsers:System.Web.UI.Page
{
受保护的无效页面加载(对象发送方、事件参数e)
{
var manager=Context.GetOwinContext().GetUserManager();
var signinManager=Context.GetOwinContext().GetUserManager();
gvUsers.DataSource=manager.Users.ToList();
gvUsers.DataBind();
}
--添加角色按钮的代码隐藏--
受保护的无效btnAddRole_单击(对象发送者,事件参数e)
{
字符串newRoleName=txtRole.Text.Trim();
如果(!Roles.RoleExists(newRoleName))
{
Roles.CreateRole(newRoleName);//这对每个新角色只起一次作用-它去哪里是任何人的猜测
}//结束创建新角色
//检查角色中的用户
var manager=Context.GetOwinContext().GetUserManager();
var user=manager.FindByName(“myusername”);
字符串username=user.username;//正确返回“myusername”
if(Membership.GetUser(“myusername”)!=null)//失败-返回null
如果(!Roles.IsUserInRole(user.UserName,newRoleName))//未进行上述检查,则返回False,表示我不在此角色中…(natch)
Roles.AddUserToRole(user.UserName,newRoleName);//此操作失败,找不到用户
}//结束添加角色
}
}
就这样 告诉过你这只是个开始。。。
编辑功能尚未创建

web.config已配置为旧的ASP.Net成员资格提供程序

但是,代码是ASP.Net标识和旧ASP.Net成员资格提供程序的组合


请免费阅读亚当·弗里曼的作品。

谢谢您的评论。我明白了,该文档中的示例也是MVC。我对MVC一无所知,所以我不确定哪些部分不适用于Web表单。示例Web.config中几乎没有任何内容与我的相同,它最初是在我创建项目时由VS构建的。我不知道为什么它会插入冲突的身份信息。我真正添加的是角色provider.ASP.Net Identity不使用provider模型,这就是为什么在web.config中看不到的原因。网站管理工具无法用于ASP.Net标识。如果要查看示例代码,可以在Visual Studio 2015中创建新的Web表单应用程序。逻辑与亚当·弗里曼的MVC非常相似。啊。。。。。。看,这就是为什么有时使用教程可以让你。。。如果他们有点过时,他们当然不知道。好的,我需要更新我的MSDN,这个愚蠢的东西上周过期了,我们的地方可能会有点慢,无法得到文件。。。然后我就可以到2015年,重新开始-(我希望标准构建的项目能够启用角色。2013年的新网站特别提到它被禁用,然后指导您使用MVC示例来学习如何启用它。遗憾的是,对我来说几乎毫无用处。MVC在形式和功能上与我完全不同,我无法翻译。好吧,那么,用2015构建的新项目与我的项目完全一样2013年。我刚刚了解到会员资格和身份