错误的ID用户-ASP NET CORE

时间:2018-07-12 12:14:52

标签: entity-framework asp.net-core asp.net-identity

我正在使用ASP.NET CORE 2.0,并且必须捕获已登录的用户ID。这是我的客户经理:

[Route("[controller]/[action]")]
public class AccountController : Controller
{
    private readonly SignInManager<ApplicationUser> _signInManager;
    private readonly ILogger _logger;
    private readonly UserManager<ApplicationUser> _userManager;

    public AccountController(SignInManager<ApplicationUser> signInManager, ILogger<AccountController> logger, UserManager<ApplicationUser> userManager)
    {
        _signInManager = signInManager;
        _logger = logger;
        _userManager = userManager;
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Logout()
    {
        await _signInManager.SignOutAsync();
        _logger.LogInformation("User logged out.");
        return RedirectToPage("./Index");
    }
}

我正在尝试通过这种方式获取ID:

ApplicationUser a = new ApplicationUser();
        CR.FuncionarioId =  a.Id;

但是他给我返回了一个完全不同的id,为什么会这样?我使用身份。然后,当我使用a.Id时,即使我是同一个用户,我也每小时都会立即带一个不同的ID,而没有带在AspnetUsers表中注册的ID。

我需要获取用户ID的页面的

代码:

protected UserManager<ApplicationUser> UserManager { get; set; }
    public RecebimentoModel(CronoParque.Model.ApplicationDbContext context)
    {
        _context = context;
    }
    [BindProperty]
    public string Message { get; set; }
    [BindProperty]
    public ContasReceberViewModel ContasReceberVM { get; set; }



    public async Task<IActionResult> OnPost()
    {
        if (ModelState.IsValid)
        {
            var CR = _context.ContasReceber.Find(ContasReceberVM.ContasReceber.Id);
            CR.Quitado = true;
            CR.ValorPago = Convert.ToDecimal(ContasReceberVM.ContasReceber.ValorPago.ToString().Replace(",","."));
            CR.FormaPagamento = ContasReceberVM.ContasReceber.FormaPagamento;
            CR.DataPagamento = DateTime.Now;
            CR.FuncionarioId = UserManager.GetUserId(HttpContext.User);
            await _context.SaveChangesAsync();
            Message = "Pagamento Realizado com Sucesso!";

            return RedirectToPage("Index");
        }
        return RedirectToPage();
    }

2 个答案:

答案 0 :(得分:2)

var user = _userManager.GetUserAsync(User);
var id = user.Result.Id;

在您的函数中尝试一下,它应该可以工作:)

答案 1 :(得分:0)

您将以Silvester Schn的方式获得ID。指出,如果ApplicationUser类继承自IdentityUser<T>。如果ApplicationUser仅实现IIdentity,则必须自己实现Id和其他属性。这是一个应按需使用的代码段。

/// <inheritdoc />
public class ApplicationUser : IdentityUser<string>, IIdentity
{
    #region ** IIdentity **
    public string AuthenticationType { get; set; } = null;
    public bool IsAuthenticated { get; set; } = false;
    public string Name { get; set; } = string.Empty;
    #endregion
}