[英]Get currently logged in user id in controller constructor ASP.NET 5 MVC6
在MVC5中,我通過覆蓋控制器中的Initialize
方法將當前登錄用戶的ID初始化為私有文件。
public class BaseControllerConstructor: Constructor
{
protected UserProfile _currentUserProfile;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
if (User.Identity.IsAuthenticated)
{
_currentUserId = User.Identity.GetUserId();
_currentUserProfile = LoadUserProfile(_currentUserId);
}
}
}
在MVC6中,控制器沒有Initialize
。
當我嘗試在構造函數中獲取當前登錄用戶的ID時, User
和HttpContext
為null
。
public BaseControllerConstructor()
{
// HttpContext is null
string _currentUserId = HttpContext.User.GetUserId();
_currentUserProfile = LoadUserProfile(_currentUserId);
}
如何在MVC6中實現此目標? 具體來說:如何獲取當前登錄用戶的用戶ID並在BaseControllerConstructor
初始化_currentUserId
?
然后在Controller動作中只需調用:
class Controller: BaseControllerConstructor
{
public ActionResult Action()
{
foo(_currentUserProfile);
}
}
更新:我使用依賴注入解決了這個問題。 請在下面查看我的答案。
我已經使用依賴項注入和IHttpContextAccessor
類訪問HttpContext.User
解決了此問題。
實現注冊為Startup.cs
。
// The interface for the service.
public interface IAccountService
{
User CurrentUser { get; }
string CurrentUserId { get; }
}
// The class which implements the interface
public class AccountService : IAccountService
{
private IHttpContextAccessor _httpContextAccessor;
// This is a custom services which has access to the business model and the data model
private IUserService _userService;
private string _currentUserId;
private User _currentUser;
public AccountService(IHttpContextAccessor httpContextAccessor, IUserService currentUser)
{
_httpContextAccessor = httpContextAccessor;
_coreServiceProvider = coreServiceProvider;
_currentUserId = null;
_currentUser = null;
}
public User CurrentUser
{
get
{
if (_currentUser != null)
{
return _currentUser;
}
if (string.IsNullOrEmpty(_currentUserId))
{
// Get the user ID of the currently logged in user.
// using System.Security.Claims;
_currentUserId = _httpContextAccessor.HttpContext.User.GetUserId();
}
if (!string.IsNullOrEmpty(_currentUserId))
{
_currentUser = _userService.Find(_currentUserId);
if (_currentUser == null)
{
string errMsg = string.Format("User with id {0} is authenticated but no user record is found.", _currentUserId);
throw new Exception(errMsg);
}
}
return _currentUser;
}
}
public string CurrentUserId
{
get
{
if (!string.IsNullOrEmpty(_currentUserId))
{
return _currentUserId;
}
// Get the user ID of the currently logged in user.
// using System.Security.Claims;
_currentUserId = _httpContextAccessor.HttpContext.User.GetUserId();
return _currentUserId;
}
}
}
在類Startup
方法ConfigureServices
注冊服務
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Register UserService a custom class which has access to the user profiles
// This is injected.
services.AddScoped<IUserService, UserService>();
// Register the IAccountService which is injected in the controller
services.AddScoped<IAccountService, AccountService>();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.