我正在谷歌搜索以在 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/