首页 文章

使用.Net Core在控制器中验证用户数据

提问于
浏览
0

我正在开发一个简单的应用程序来管理一些静态IP地址,以此来学习如何使用用户和 生产环境 环境的身份验证构建完整的.Net Core应用程序 .

我从Visual Studio 2015中的.Net Core Web应用程序模板开始,其中包括Identity Framework Core和Entity Framework Core . 我已经构建了以下模型并使用CRUD页面生成控制器 . 所有这一切都很有效 .

到目前为止,我可以使用内置代码登录/注册/注销等没有问题 . 我希望这些数据是用户特定的,因此用户A获取他们的地址,而用户B获得他们的地址 . 因此,这将涉及Identity Framework表的某种外键,因此它可以将IP地址与用户匹配,然后显示它们 . 我想知道用.Net Core处理这个问题的最佳方法是什么?我无法找到任何特定于.Net Core的示例 .

模型:

public class IpAddress
{
    [Key]
    public int id { get; set; }

    [Required]
    [MaxLength(255)]
    public string hostname { get; set; }

    [MinLength(9)]
    [MaxLength(21)]
    public string ipv4 { get; set; }

    [MaxLength(45)]
    public string ipv6 { get; set; }

    [Required]
    public bool vm { get; set; }

    [Required]
    public bool container { get; set; }

    [Required]
    public bool docker { get; set; }

    [Required]
    public string operating_system { get; set; }

    [Required]
    public string description { get; set; }
}

控制器的第一部分(索引和详细信息路径):

[Authorize]
public class IpAddressesController : Controller
{
    private readonly IpAddressContext _context;

    public IpAddressesController(IpAddressContext context)
    {
        _context = context;    
    }

    // GET: IpAddresses
    public async Task<IActionResult> Index()
    {
        return View(await _context.IpAddresses.ToListAsync());
    }

    // GET: IpAddresses/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var ipAddress = await _context.IpAddresses.SingleOrDefaultAsync(m => m.id == id);
        if (ipAddress == null)
        {
            return NotFound();
        }

        return View(ipAddress);
    } 
 ...

就像我说的那样,我认为它就像在模型中添加外键一样简单,然后使用基于该外键的Linq查询获取控制器中的数据,对吧?我对Linq不太满意,所以任何帮助都会很棒 . 如果有帮助,我可以肯定地提供更多代码 .

1 回答

  • 0

    你是对的 . 您需要在IpAddress表上添加一个外键(将您链接到用户表):

    [ForeignKey("ApplicationUser"), Column("Id")]
    public int UserId { get; set; }
    

    然后在AspNetUsers表上添加信息以匹配

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

    然后,您将能够使用LINQ获取用户的IP地址信息,例如:

    _context.IpAddresses.SingleOrDefaultAsync(m => m.UserId == userIid);
    

相关问题