首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当前在控制器构造函数ASP.NET 5 MVC6中登录用户id

当前在控制器构造函数ASP.NET 5 MVC6中登录用户id
EN

Stack Overflow用户
提问于 2016-02-13 10:46:43
回答 1查看 3.3K关注 0票数 4

在MVC5中,我通过在控制器中重写Initialize方法,将当前登录用户的ID初始化为私有字段。

代码语言:javascript
复制
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时,UserHttpContextnull

代码语言:javascript
复制
public BaseControllerConstructor()
{
    // HttpContext is null      
    string _currentUserId = HttpContext.User.GetUserId();
    _currentUserProfile = LoadUserProfile(_currentUserId);
}

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

然后在Controller操作中只需调用:

代码语言:javascript
复制
class Controller: BaseControllerConstructor
{
    public ActionResult Action()
    {
        foo(_currentUserProfile);
    }       
}

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

EN

回答 1

Stack Overflow用户

发布于 2016-02-13 12:21:12

我已经使用依赖注入和IHttpContextAccessor类来访问HttpContext.User来解决这个问题。

实现注册为Startup.cs的服务。

代码语言:javascript
复制
// 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中注册服务

代码语言:javascript
复制
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>();
    }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35378910

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档