gpt4 book ai didi

c# - 将依赖项注入(inject) .net 核心中的自动映射器配置文件 - IHttpContextAccessor 返回 null

转载 作者:太空狗 更新时间:2023-10-29 22:35:58 26 4
gpt4 key购买 nike

目标:IHttpContextAccessor 作为依赖注入(inject)到 autmapper 配置文件的构造函数中

原因:我需要传入当前用户的身份名称作为构建我的域对象之一的一部分

问题获取到的User身份始终为null

到目前为止我有什么?

Startup.cs

mc.AddProfile(new DtoToOtherProfile(new HttpContextAccessor()));

//OR

var mapperConfiguration = new MapperConfiguration(mc =>
{
IServiceProvider provider = services.BuildServiceProvider();
mc.AddProfile(new DtoToOtherProfile(provider.GetService<IHttpContextAccessor>()));
});

DtoToOtherProfile.cs

 public DtoToOtherProfile(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;

CreateMap<MyDto, MyOther>()
.ConstructUsing(myDto => new myOther(myDto.prop1, myDto .prop2, _httpContextAccessor.HttpContext.User.Identity.Name)); // the name is what i intend to pass
// other mapping
}

Controller.cs

  public async Task<IActionResult> Create([FromBody]MyDto model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

// save campaign
var myOtherModel = _mapper.Map<MyOther>(model);
// myOtherModel.UserName is always null
// rest
}

有什么东西不见了吗?请指点?

最佳答案

我认为正确的做法不是在 Profile 中注入(inject) IHttpContextAccessor 而是创建一个单独的 IValueResolver 并在那里注入(inject) IHttpContextAccessor。所以只需执行以下操作,我想在其中获取用户对 httpcontext 的声明

在你的StartUp.cs里面ConfigureServices添加

 services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddAutoMapper();

使用您的映射创建配置文件

public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<QueryUniqueDto, QueryUnique>()
.ForMember(s=>s.UserClaim,opt=>opt.MapFrom<IdentityResolver>());
}
}

创建IValueResolver

public class IdentityResolver : IValueResolver<QueryUniqueDto, QueryUnique, UserClaim>
{
private IHttpContextAccessor _httpContextAccessor;

public IdentityResolver(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}

public UserClaim Resolve(QueryUniqueDto source, QueryUnique destination, UserClaim destMember, ResolutionContext context)
{
return Helper.GetClaimsFromUser(_httpContextAccessor.HttpContext?.User.Identity as ClaimsIdentity);
}
}

这太棒了!!!

关于c# - 将依赖项注入(inject) .net 核心中的自动映射器配置文件 - IHttpContextAccessor 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43729675/

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