c# - 在 Controller 中获取 ApplicationUser

标签 c# asp.net-core identity entity-framework-core

我正在谷歌搜索以在 ASP.NET Identity 3.0 的 Controller 中获取应用程序用户,但我只找到 5 及以下的结果。

我正在尝试获取 ApplicationUser 属性,但我根本无法获取 ApplicationUser。我想这很容易,因为我是唯一遇到这个问题的人。

using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.AspNet.Identity;
using System.Security.Claims;

namespace ApplicationUserFMLTest.Controllers
{
    public class CustomClassController : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;

        private ApplicationDbContext _context;

        public CandidatesController(ApplicationDbContext context, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
        {
            _context = context;
            _userManager = userManager;
            _signInManager = signInManager;
        }

        // GET: CustomClass
        public async Task<IActionResult> Index()
        {
            ApplicationUser currentUser = _userManager.FindByIdAsync(User.Identity.GetUserId()).Result;


            if (currentUser.PropBool)
                return View(currentUser);


            return View();
        }

        // ManageController function
        private async Task<ApplicationUser> GetCurrentUserAsync()
        {
            return await _userManager.FindByIdAsync(HttpContext.User.GetUserId());
        }

    }
}

最佳答案

Joe 的回答会很好,但请注意还有一个更简单的方法,它直接采用 ClaimsPrincipal 实例并在内部调用 GetUserId:

var user = await _userManager.GetUserAsync(User);

关于c# - 在 Controller 中获取 ApplicationUser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39544372/

相关文章:

c# - 如何使用 ScriptSharp 动态生成 javascript?

c# - Outlook 电子邮件中 ​​HTML 页面的格式丢失

json - 为什么使用Ajax时输入值为NULL?(ASP.NET CORE)

Asp.net 身份密码哈希

c# - Visual Studio 2008 - 将构建时的文件移动到 bin/

asp.net-core - asp.net 核心 Begin Collection Item 核心不适用于剑道控件

c# - 标签助手 asp-route- 不工作 - Razor Pages(.Net Core 3 预览版 5)

java - 可以控制 Java 中对象的身份吗?如果可以,如何控制?

C# 类自动递增 ID

javascript - 如何使用javascript修改gridview单元格值