c# - 如何根据 asp.net core 中 AutoMapper 中的用户角色有条件地映射/忽略属性
问题描述
我在用着AutoMapper.Extensions.Microsoft.DependencyInjection 7.0.0
我只需要为具有特定角色的用户映射属性,否则在我的 asp.net core 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())));
}
}
但是我得到以下无参数少构造函数异常。
没有为“BranchProfile”类型定义无参数构造函数
有更好的方法来访问HttpContext
这个条件映射吗?请协助
解决方案
这是我如何使用IMappingAction
. IMappingAction
支持 DI 和我注入IHttpContextAccessor
并用于AfterMap
基于用户角色映射/拒绝(重置为原始值)映射。
映射配置文件:
public class BranchProfile : Profile
{
public BranchProfile()
{
CreateMap<Branch, BranchEditViewModel>()
.AfterMap<MapOnlyForMasterUserAction>();;
}
}
映射动作:
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;
}
}
}
推荐阅读
- javascript - moment.js,比较 diff 与天与年
- osgearth - 在 osg 中使用三个向量设置牛旋转和定位
- r - RTools 不工作 - 无法安装源包
- javascript - Express cookie 检查抛出 TypeError
- python - read values from text file in python
- rust - `Option 的动态替换
>>>` - java - 为什么我的程序忽略了scanner.nextLine()?
- oracle-apex - Oracle apex 升级错误:在 Oracle VM 上从 19 升级到 21.1 时,出现以下错误:ORA-22288: file or LOB operation FILEOPEN failed
- python - 我想将 python 输出列表转换为数组
- javascript - 在图像 HTML/Javascript 上书写