如何使用 Web API 2 + AspNet Identity 2 扩展 IdentityRole

2023-12-26

我正在尝试扩展最新版本的 Visual Studio 2013 中的 Web API 2(包含个人帐户)模板中提供的 AspNet IdentityRole 类。当我点击 /api/roles 时,它返回一个空数组

身份模型

namespace API.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser<string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim>, IUser, IUser<string>
{
    [NotMapped]
    public virtual UserProfile Profile { get; set; }

    public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }

    //public virtual List<ApplicationUserRole> ApplicationRoles { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager,
        string authenticationType)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        ClaimsIdentity userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
        // Add custom user claims here
        return userIdentity;
    }
}

public class ApplicationRole : IdentityRole<string, ApplicationUserRole>
{
    public ApplicationRole() : base() { }

}

public class ApplicationUserRole : IdentityUserRole<string>
{
    public ApplicationUserRole()
        : base()
    { }

    public virtual ApplicationRole Role { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser,ApplicationRole,string,IdentityUserLogin,ApplicationUserRole,IdentityUserClaim> 

{

     public ApplicationDbContext()
        : base("DefaultConnection")
    {
        base.Configuration.ProxyCreationEnabled = false;
    }

     public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

}

身份配置

namespace API
{
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.

public class ApplicationUserManager : UserManager<ApplicationUser, string>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,
        IOwinContext context)
    {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));

        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };
        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };
        IDataProtectionProvider dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider =
                new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        }
        return manager;
    }
}



public class ApplicationRoleManager : RoleManager<ApplicationRole, string>
{
    public ApplicationRoleManager(IRoleStore<ApplicationRole, string> store)
        : base(store)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options,
        IOwinContext context)
    {
        var manager = new ApplicationRoleManager(new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
        return manager;
    }

}

}


你的错误就在这里

ApplicationDbContext : IdentityDbContext<ApplicationUser>

您的数据库上下文的范围是IdentityDbContext<ApplicationUser>这是基于

IdentityDbContext<TUser, IdentityRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>

ApplicationDbContext 将生成IdentityRole当你真正想要的时候ApplicationRole作为你的角色。

将您的 ApplicationDbContext 更改为

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim>
{

 public ApplicationDbContext()
    : base("DefaultConnection", false)
 {
    base.Configuration.ProxyCreationEnabled = false;
 }

 public static ApplicationDbContext Create()
 {
    return new ApplicationDbContext();
 }
}

you don't have to overide OnModelCreating and add property Roles in this point.

由于您在 ApplicationUserRole 中有导航属性,因此您应该添加配置映射

protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<ApplicationUserRole>().HasRequired(ur => ur.Role).WithMany().HasForeignKey(ur => ur.RoleId);
}

IdentityModel.cs 应该是这样的:

public class ApplicationUserRole : IdentityUserRole<string>
{
    public ApplicationUserRole()
        : base()
    { }

    public virtual ApplicationRole Role { get; set; }
}

public class ApplicationRole : IdentityRole<string, ApplicationUserRole>
{
    public ApplicationRole() : base() { }

    public ApplicationRole(string name, string description)
        : base()
    {
        this.Name = name;
        this.Description = description;
    }

    public string Description { get; set; }
}

public class ApplicationUser : IdentityUser<string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim>
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim>
{

    public ApplicationDbContext()
        : base("DefaultConnection")
    {
        base.Configuration.ProxyCreationEnabled = false;
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
    protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<ApplicationUserRole>().HasRequired(ur => ur.Role).WithMany().HasForeignKey(ur => ur.RoleId);
    }
}

Identityconfig.cs 应该是这样的:

public class ApplicationUserStore : UserStore<ApplicationUser, ApplicationRole, string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim>, IUserStore<ApplicationUser>
{
    public ApplicationUserStore(ApplicationDbContext context)
        : base(context)
    {
    }   
}

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    {
        var manager = new ApplicationUserManager(new ApplicationUserStore(context.Get<ApplicationDbContext>()));
        ....
    }
}
public class ApplicationRoleStore : RoleStore<ApplicationRole, string, ApplicationUserRole>
{
    public ApplicationRoleStore(ApplicationDbContext context)
        : base(context)
    {

    }
}
public class ApplicationRoleManager : RoleManager<ApplicationRole, string>
{
    public ApplicationRoleManager(IRoleStore<ApplicationRole, string> store)
        : base(store)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options,
        IOwinContext context)
    {
        var manager = new ApplicationRoleManager(new ApplicationRoleStore(context.Get<ApplicationDbContext>()));
        return manager;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Web API 2 + AspNet Identity 2 扩展 IdentityRole 的相关文章

随机推荐

  • OpenCV - 如何将 Mat 推回到队列中?

    我正在尝试将视频帧放入双端队列中 这段代码不起作用 因为队列的后部和前部都与当前帧相同 deque
  • Heroku 上的 Ruby 版本未升级

    我已在 Heroku 上将应用程序从 ruby 1 9 2 升级到 ruby 1 9 3 我关注了heroku上关于它的文章 https devcenter heroku com articles ruby versions https d
  • 为什么 Double.NaN 在包装在 Double 实例中时等于自身?

    From 这个问题 https stackoverflow com questions 471296 how can while i i be a non infinite loop我了解到 Double NaN 不等于其自身 我正在为自己
  • 如何将 uint256 变量转换为 int256 变量?

    我试图打印uint timeStamp通过输入return timeStamp 就在下面return price 从这段代码 pragma solidity 0 6 7 import chainlink contracts src v0 6
  • 如何为 Spring Web Flow 定义自定义消息源?

    spring webflow 文档提到 他们将消息添加到流的方法是在流内的文件 messages properties 中定义与该流相关的所有消息 国际化消息在 Spring MessageSource 访问的消息束中定义 要创建特定于流的
  • 在 Java 中确定运行时的 AWS lambda 名称

    我真的很喜欢从 Java 中调用 AWS lambdas 的方法这篇博文 https java awsblog com post Tx2J2LPKTTVU93H Invoking AWS Lambda Functions from Java
  • 字符串操作没有内存泄漏?

    我想进行一系列字符串替换来删除 xml 转义字符 例如 amp 1 是否有现有的 UIKit 函数可以做到这一点 2 如果没有 在不泄漏内存的情况下最好的方法是什么 想法是这样的 NSString unescape NSString str
  • 如何在 contenteditable 元素中使用 ngControl?

    我该如何使用ngControl in contenteditable元素 例如 我想要 td td 通过绑定 将其绑定到模型驱动的 表单 表 我创造了他formBuilder基于模式 从服务器检索 目前我认为这不起作用 因为 td 和其他
  • htmltextwriter 和跨站点脚本

    只是一个简单的问题 我被要求浏览一个 vb 应用程序并修复所有可能发生跨站点脚本的地方 我将 是的 它确实可以保护您在写入 HTML 文档时免受 XSS 侵害 但是HtmlTextWriter WriteEncodedText https
  • C# Func(T) 不接受 ref 类型输入参数

    Can Func lt gt 接受 C 中通过引用传递的参数 static void Main Func
  • Heroku:ModuleNotFoundError:没有名为“请求”的模块

    我正在尝试将 Django 程序部署到 Heroku 该应用程序在我的本地计算机上成功运行 该计算机使用 Anaconda 和 Python 3 5 我无法让它推送到 Heroku 根据命令 gt git push heroku maste
  • 使用多设备混合应用程序构建 Visual Studio Cordova 应用程序时发生错误

    我收到 3 个致命错误 我也安装了android SDK 19 有任何想法吗 An error occurred while listing Android targets C Project AngularJS ToDo Sample f
  • 不是 JAX-WS 中的有效服务异常

    我正在参考http www mkyong com webservices jax ws jax ws hello world example http www mkyong com webservices jax ws jax ws hel
  • 使用 sqlplus 命令行隐藏纯文本密码

    我希望使用 sqlplus 命令 并在视图中隐藏密码 这样它就不会显示在 ps ef 命令中 我知道互联网博客上提供了很多解决方案 但大多数似乎都需要管理员权限 并且我对此服务器的访问受到限制 其余的似乎对我不起作用 我当前使用的命令如下
  • 在附加到 Refit 客户端的 Polly 策略中使用 ILogger

    我一直在尝试遵循以下指示这篇博文 https www stevejgordon co uk passing an ilogger to polly policies将 ILogger 传递到我的重试策略 以便记录有关重试错误的信息 博客中的
  • ember-data 作为 d3 的数据

    我想使用我的 emberdata 作为在 d3 中创建对象的数据 我尝试将控制器模型中的项目转换为新的 javascript 对象 并将这个新数组提供给 d3 数据 这是代码 App GraphicsView Ember View exte
  • smart-table - 如何重置过滤器集合?

    Angular 和智能表新手 此智能表设置可以正常工作并正确过滤 但尝试重置或清除过滤器不会重新过滤表 为什么不 使用 ng model 绑定更新输入是否不会触发 smart table 正在寻找的监视 Plunker 可以在这里找到 ht
  • h1 和跨度

    在我的 html 中使用 h1 h6 标签时 我不断收到 w3c 验证器上的错误消息 我对此很陌生 我已经尝试了很多次来解决这个问题 但我不能 该文本在我的网站上显示得很好 但无法验证 我该如何解决这个问题 错误信息如下 第 34 行 第
  • 如何在CodeIgniter中获取表的最后一条记录?

    如何在Codeigniter中获取表的最后一条记录 我的表名称是 post 我想获取该表中最后一条记录的最后一个 id 或下一个 id recommended don t use from getting rows insted of pl
  • 如何使用 Web API 2 + AspNet Identity 2 扩展 IdentityRole

    我正在尝试扩展最新版本的 Visual Studio 2013 中的 Web API 2 包含个人帐户 模板中提供的 AspNet IdentityRole 类 当我点击 api roles 时 它返回一个空数组 身份模型 namespac