代码之家  ›  专栏  ›  技术社区  ›  Sergio

如何从Automapper配置文件中获取用户标识

  •  1
  • Sergio  · 技术社区  · 8 年前

    我有一个NET Core应用程序,需要获取当前用户令牌,以便使用Automapper映射对象。

    这是我的网络核心 控制器 :

    public async Task<IActionResult> Add([FromBody] EnrollSkill request)
    {
        var model = _autoMapper.Map<Domain.Entities.UserSkill>(request);
    
        var response = await _userService.AddSkillAsync(model);
    
        return Ok();
    }
    

    请注意,我正在尝试映射 注册技能 查看模型到 用户技能 域模型。

    这是我的 注册技能 类别:

    public class EnrollSkill
    {
        public string Id { get; set; } // Skill Id (not user Id)
        public int KnowledgeLevel { get; set; }
        public int Order { get; set; }
    }
    

    这是我的 用户技能 类别:

    public class UserSkill : Base
    {
        public int KnowledgeLevel { get; set; }
        public int Order { get; set; }
        public DateTime CreatedDate { get; set; }
    
        public string UserId { get; set; }
        public User User { get; set; }
    
        public string SkillId { get; set; }
        public Skill Skill { get; set; }
    }
    

    在我的存储库服务中,我需要填充UserId来调用SaveChangesAsync()

    此用户ID存在于控制器中,因为我可以通过以下方式读取用户声明:

    User.Claims
    

    现在,我在Automapper中有一个配置文件:

    CreateMap<EnrollSkill, UserSkill>().
        BeforeMap((from, to) =>
        {
            to.UserId = "12345"
        });
    

    但是,如何在Automapper中正确读取该值?最好的方法是什么?

    我试图用一个名为SetUserId的方法在controller中填充此UserId,但我认为这是一个错误的解决方案,因为我弄乱了我的域实体:

    var model = _autoMapper.Map<Domain.Entities.UserSkill>(request).SetUserId(CurrentUserId);
    

    谢谢

    1 回复  |  直到 8 年前
        1
  •  4
  •   Sergio    8 年前

    我认为最好的解决方案是注入IHttpContextAccessor

    在我的 启动 I类通过扩展方法添加了Automapper服务,我传递了IHttpContextAccessor:

    services.AddAutomapperConfiguration(_serviceProvider.GetService<IHttpContextAccessor>());
    

    现在,在我的 扩展方法 ,我将IHttpContextAccessor传递到我的Automapper配置文件:

    public static void AddAutomapperConfiguration(this IServiceCollection services, 
        IHttpContextAccessor httpContextAccessor)
    {
        var automapperConfig = new MapperConfiguration(configuration =>
        {            
            configuration.AddProfile(new Profiles(httpContextAccessor));
        });
    
        var autoMapper = automapperConfig.CreateMapper();
    
        services.AddSingleton(autoMapper);
    }
    

    最后,在我的 轮廓 我通过从IHttpContextAccessor读取用户声明的助手获取用户Id

    public class Profiles : Profile
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
    
        public Profiles(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
    
            CreateMap<Models.User.EnrollSkill, UserSkill>()
                .AfterMap((src, dest) =>
                {
                    dest.UserId = IdentityHelper.GetClaimValue(_httpContextAccessor, IdentityHelper.Claims.Id);
                });
    
        }
    }
    

    我不知道这是否是最好的解决方案,但它工作正常