gpt4 book ai didi

c# - 在 Controller 构造函数 ASP.NET 5 MVC6 中获取当前登录的用户 ID

转载 作者:行者123 更新时间:2023-12-03 21:25:53 24 4
gpt4 key购买 nike

在 MVC5 中,我通过覆盖 Initialize 将当前登录用户的 ID 初始化为私有(private)文件。 Controller 中的方法。

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 Controller 中没有 Initialize .

当我尝试在构造函数中获取当前登录用户的 ID 时, UserHttpContextnull .
public BaseControllerConstructor()
{
// HttpContext is null
string _currentUserId = HttpContext.User.GetUserId();
_currentUserProfile = LoadUserProfile(_currentUserId);
}

如何在 MVC6 中实现这一点?具体:如何获取当前登录用户的用户ID并初始化 _currentUserIdBaseControllerConstructor ?

然后在 Controller Action 中调用:
class Controller: BaseControllerConstructor
{
public ActionResult Action()
{
foo(_currentUserProfile);
}
}

更新:我使用依赖注入(inject)解决了这个问题。请看下面我的回答。

最佳答案

我已经使用依赖注入(inject)和 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>();
}
}

关于c# - 在 Controller 构造函数 ASP.NET 5 MVC6 中获取当前登录的用户 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35378910/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com