【问题标题】:how to limit GET api call based on user properties如何根据用户属性限制 GET api 调用
【发布时间】:2015-11-07 04:09:35
【问题描述】:

ApplicationUser 和模型“公司”之间存在多对多关系 我希望登录用户只能检索分配给其公司的文档。

使用这个 linq 语句

   public IEnumerable<DocumentResult> GetDocuments()
    {
        var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
        var user = manager.FindById(User.Identity.GetUserId());
        return db.Documents
            .Where(j => j.Company.Name == user.Companies)
            .ToResults();
    }

我收到了

运算符“==”不能应用于“字符串”和“ICollection”类型的操作数

型号

  public class Company
{
    public Company()
    {
        Users = new HashSet<ApplicationUser>();
    }
    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<ApplicationUser> Users { get; set; } 
}

应用用户

   public class ApplicationUser : IdentityUser
{
    public ApplicationUser()
    {
        Companies = new HashSet<Company>();
    }
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
    public ICollection<Company> Companies { get; set; }
    public string FullName { get; set; }
    public string ProfilePicUrl { get; set; }

}

【问题讨论】:

  • 首先想到的是 .Where(j => user.Companies.Contains(j.Company.Name))
  • 现在说不能将字符串转换为models.company
  • 那么,j.Company.Nameuser.Companies 中的公司之一吗?例如,您是否需要在该集合中选择其中一家公司进行比较/或在该集合中搜索匹配项?
  • 我用两个模型更新了帖子。是的,每个文件都有一个公司名称。可以为每个用户分配一个或多个公司。

标签: c# asp.net-mvc linq asp.net-web-api


【解决方案1】:

考虑使用这样的代码:

db.Documents
        .Where(j => user.Companies.Any(uc=>uc.Name == j.Company.Name));
        .ToResults();

【讨论】:

    【解决方案2】:

    错误信息很清楚。

    user.Companies 是一个集合,j.Company.Name 是字符串。

    您不能使用“==”来比较不同类型的字符串。

    【讨论】:

    • 那我用什么来比较?
    • 这应该是一条评论。它没有回答问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多