在我的控制器中使用身份作为过滤机制

use the Identity as filtermechanism in my Controller

我有一个控制器,它从 Mysql 数据库中获取所有项目并将它们放入我的模型中。 此方法在我的 Index() 中调用,因此它可以在 gridview 中显示所有项目。

我希望能够使用 Login.cshtml 中使用的 'company number' 登录网页。 公司编号也需要在我的 Contoller 中使用(我认为)。它将在 SQL 查询中使用,因此公司只能看到他们自己的项目。 但是我怎样才能让控制器能够获取信息?

public List<ContainerInfo> TablesColumnDisplay()
{
  //string on = the connectionstring
  using SqlCommand SqlComm = new SqlCommand($"SELECT * FROM TheItemList"); //I think this needs WHERE company_number = '{Identity.Companynumber}'
  using (SqlDataAdapter sda = new SqlDataAdapter())
    {
      {
        SqlComm.Connection = SqlConn;
        SqlConn.Open();
        sda.SelectCommand = SqlComm;

        SqlDataReader sdr = SqlComm.ExecuteReader();
        while (sdr.Read())
        {
          ItemList item = new ItemList();
          //The entire sdr reader that puts all the items into the models
        }
}

还是我错得离谱,我必须为此制定一个更糟糕的方法吗?我对如何解决这个问题有点迷茫。

编辑 我正在使用标准脚手架身份区域,我已经在其中更改了一些模型项目。 在我的 Login.cshtml 中是一个标准表格,它要求 company_number、密码以及是否记住我。

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _signInManager.PasswordSignInAsync(Input.company_number.ToString(), Input.Password, Input.RememberMe, lockoutOnFailure: false);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return LocalRedirect(returnUrl);
                }
                if (result.RequiresTwoFactor)
                {
                    return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return RedirectToPage("./Lockout");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return Page();
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }

我通过查看 stackoveflow 解决了这个问题。

请注意,我必须使用 'System.Security.Claims' 才能访问登录用户。 您需要一个包含当前登录用户的变量。这可以通过 User.FindFirst(ClaimTypes.Name).Value 找到;

然后您可以在 SQL 查询中通过在开头使用 $ 符号来使用该变量。允许您在查询中使用变量。

using System.Security.Claims;

//This gives me the value of the first ClaimTypes.Name(which in my case: is 123456)
int Username = Convert.ToInt32(User.FindFirst(ClaimTypes.Name).Value);
public List<ContainerInfo> TablesColumnDisplay()
{
  //string conn = the connectionstring
  using SqlCommand SqlComm = new SqlCommand($"SELECT * FROM TheItemList WHERE company_number = {Username}"); 
  using (SqlDataAdapter sda = new SqlDataAdapter())
    {
      {
        SqlComm.Connection = SqlConn;
        SqlConn.Open();
        sda.SelectCommand = SqlComm;

        SqlDataReader sdr = SqlComm.ExecuteReader();
        while (sdr.Read())
        {
          ItemList item = new ItemList();
          //The entire sdr reader that puts all the items into the models
        }
}