ASP .NET Core 如何使用主键值获取userId值?

ASP .NET Core How to get userId value using the primary key value?

我需要对应用程序进行验证,我需要检查文件是否属于发出请求的用户。如果没有,用户将收到 NotFound 响应。

我正在尝试使用 主键 值获取拥有该文件的 userId 的字符串值,并与值进行比较提出请求的 userId

问题是即使拥有该文件的用户也会收到 NotFound 响应。

我想我没有正确获取 user2 字符串的值。 我该如何解决这个问题?

[HttpGet("{id}")]
        public ActionResult<File> GetShare(int id)
        {

            string userId = User.Claims.First(c => c.Type == "UserID").Value;
            string user2 = _context.File.Where(t => t.FileId == id).Select(t => new File()
            {
                UserId = t.UserId

            }).ToString();

            if (userId != user2)
            {
                return NotFound();
            }
            else
            {
                return _context.File.SingleOrDefault(t => t.FileId == id);
            }
        }

数据库table是基于这个模型制作的:

public class File
    {
        [Key]
        public int FileId { get; set; }

        [Column(TypeName = "varchar(30)")]
        [Required]
        [MinLength(1)]
        public string Name { get; set; }

        [Column(TypeName = "varchar(50)")]
        public string Description { get; set; }

        [Column(TypeName = "varchar(50)")]
        public string Syntax { get; set; }

        [Column(TypeName = "smalldatetime")]
        public DateTime LastModified { get; set; }

        [Column(TypeName = "smalldatetime")]
        public DateTime? ExpirationDate { get; set; }

        [Column(TypeName = "varchar(MAX)")]
        [Required]
        [MinLength(1)]
        public string Content { get; set; }

        [Column(TypeName = "varchar(MAX)")]
        public string Tags { get; set; }

        public string UserId { get; set; }
        [ForeignKey("UserId")]
        public virtual UserAccount UserAccount { get; set; }

    }
}

您的 select 代码有误。

当你这样做时

string user2 = _context.File
                       .Where(t => t.FileId == id)
                       .Select(t => new File() { UserId = t.UserId })
                       .ToString();

您基本上是在返回一个 IQueryable<File> 并调用一个 ToString() returns 一些意外结果,并且该字符串与用户 ID 相去甚远。

一种可能的解决方案是

[HttpGet("{id}")]
public ActionResult<File> GetShare(int id)
{
    string userId = User.Claims.First(c => c.Type == "UserID").Value;
    var file = _context.File.FirstOrDefault(t => t.FileId == id);

    if(file == null)
    {
        return NotFound();
    }

    if (userId != file.UserId)
    {
        return NotFound();
    }
    
    return file;
}