2016-09-17 61 views
3

我正在谷歌獲取ASP.NET身份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()); 
     } 

    } 
} 
+0

什麼是你的代碼有問題嗎?你有錯誤嗎? –

+0

它表示身份不包含'GetUserId'的定義,並且最佳擴展方法ovreload'PrincipalExtensions.GetUserId(ClaimsPrincipal)'需要類型爲'ClaimsPrincipal'的接收者, – StuiterSlurf

回答

5

喬的回答將正常工作,但要注意也有一個更簡單的方法,即直接採取ClaimsPrincipal實例並調用GetUserId內部:

var user = await _userManager.GetUserAsync(User); 
2

你應該改變你的代碼是這樣的:

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


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


    return View(); 
} 

the way to get the userid changed back in RC2

相關問題