將ApplicationUser放入控制器中

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

我正在google以獲取ASP.NET Identity 3.0中的控制器中的應用程序用戶,但我只找到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);

熱門答案

你應該改變你的代碼:

public async Task<IActionResult> Index()
{
    var userId = _userManager.GetUserId(User);
    ApplicationUser currentUser = await _userManager.FindByIdAsync(userId);


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


    return View();
}

在RC2中更改用戶標識的方法



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因