如何根据 asp.net 核心中 AutoMapper 中的用户角色有条件地 map/ignore 属性

How to conditionally map/ignore properties based on user role in AutoMapper in asp.net core

我正在使用 AutoMapper.Extensions.Microsoft.DependencyInjection 7.0.0

我只需要为具有特定角色的用户映射属性,否则在我的 asp.net 核心 3.0 项目中忽略使用 automapper 的映射。

这是我试过的,

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())));
    }
}

但我得到以下无参数构造函数异常。

No parameterless constructor defined for type 'BranchProfile'

访问 HttpContext 以执行此条件映射的任何更好方法?请协助

以下是我如何使用 IMappingAction 实现功能。 IMappingAction 支持 DI,我根据用户角色注入 IHttpContextAccessor 并使用 AfterMap 到 map/reject(重置为原始值)映射。

映射配置文件:

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;
        }
    }
}