我正在使用AutoMapper.Extensions.Microsoft.DependencyInjection 7.0.0
我只需要为具有特定角色的用户映射属性,否则在asp.net core 3.0项目中使用自动映射器忽略映射。
这是我尝试过的,
public class BranchProfile : Profile
{
private readonly HttpContext _httpContext;
public BranchProfile(IHttpContextAccessor httpContextAccessor)
{
_httpContext = httpContextAccessor.HttpContext;
CreateMap<Branch, BranchEditViewModel>()
.ForMember(dest => dest.Lock, opt => opt.Condition(src => _httpContext.User.IsInRole(UserRoles.Master.ToString())))
.ForMember(dest => dest.ExpireOn, opt => opt.Condition(src => _httpContext.User.IsInRole(UserRoles.Master.ToString())));
}
}
但是我得到以下没有参数的构造函数异常。
没有为'BranchProfile'类型定义无参数构造函数
访问HttpContext
进行此条件映射的任何更好的方法?请协助
这里是我如何使用IMappingAction
实现功能的方法。 IMappingAction
支持DI,我注入了IHttpContextAccessor
,并使用AfterMap
根据用户角色映射/拒绝(重置为原始值)映射。
映射配置文件:
public class BranchProfile : Profile
{
public BranchProfile()
{
CreateMap<Branch, BranchEditViewModel>()
.AfterMap<MapOnlyForMasterUserAction>();;
}
}
IMappingAction:
public class MapOnlyForMasterUserAction : IMappingAction<BranchEditViewModel, Branch>
{
private readonly IHttpContextAccessor _httpContextAccessor;
public MapOnlyForMasterUserAction(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
}
public void Process(BranchEditViewModel source, Branch destination, ResolutionContext context)
{
if (_httpContextAccessor.HttpContext.User.IsInRole(IdentityEnums.UserRoles.Master.ToString()))
{
destination.Lock = source.Lock.ToString();
destination.ExpireOn = source.ExpireOn.ToShortDateString();
}
else
{
destination.Lock = destination.Lock;
destination.ExpireOn = destination.ExpireOn;
}
}
}