在ASP.NET中在哪里配置此自动映射
我使用的是普通的ASP.NET而不是.NET内核 目前,映射工作正常,但我将以下初始化代码放在控制器中并在控制器中调用,这可能不是一个好主意 因此,尝试创建一个新类进行初始化,然后从Global.asax调用。但我有一个问题-“映射器”不包含“初始化”的定义。看起来我使用的是旧版本的AutoMapper或其他东西。我在doco上读到了这一点:每个AppDomain只能进行一次配置。这意味着放置配置代码的最佳位置是应用程序启动,例如ASP.NET应用程序的Global.asax文件。通常,配置引导程序类位于其自己的类中,并且该引导程序类是从startup方法调用的。引导程序类应该构造一个MapperConfiguration对象来配置类型映射 那么这与我目前的尝试有什么关系呢 我的下一个问题是,一旦这个设置正确,我如何在控制器中调用它呢 非常感谢您的反馈/评论 谢谢 控制器中的当前配置(可能不是一个好主意,但可以正常工作):在ASP.NET中在哪里配置此自动映射,asp.net,.net,asp.net-web-api,automapper,Asp.net,.net,Asp.net Web Api,Automapper,我使用的是普通的ASP.NET而不是.NET内核 目前,映射工作正常,但我将以下初始化代码放在控制器中并在控制器中调用,这可能不是一个好主意 因此,尝试创建一个新类进行初始化,然后从Global.asax调用。但我有一个问题-“映射器”不包含“初始化”的定义。看起来我使用的是旧版本的AutoMapper或其他东西。我在doco上读到了这一点:每个AppDomain只能进行一次配置。这意味着放置配置代码的最佳位置是应用程序启动,例如ASP.NET应用程序的Global.asax文件。通常,配置引导
private MapperConfiguration configuration = new MapperConfiguration(cfg => {
cfg.CreateMap<Activity, ActivityDTO>()
.ForMember(dst => dst.OwnerId, src => src.MapFrom(ol => ol.User.Id))
.ForMember(dst => dst.OwnerName, src => src.MapFrom(ol => ol.User.FirstName + " " + ol.User.LastName))
.ForMember(dst => dst.CategoryName, src => src.MapFrom(ol => ol.Category.Name));
cfg.CreateMap<ActivityDTO, Activity>()
.ForMember(dst => dst.UserId, opt => opt.MapFrom(src => HttpContext.Current.User.Identity.GetUserId()));
});
var activitiesDTO = await (db.Activities
.Include(b => b.User)
.Include(c => c.Category)
.Where(q => q.UserId == userId)
.ProjectTo< ActivityDTO>(configuration)
.AsQueryable()
.ApplySort(sortfields)
.Skip((pageNumber - 1) * pageSize).Take(pageSize)).ToListAsync();
public class AutomapperWebProfile : AutoMapper.Profile
{
public AutomapperWebProfile()
{
CreateMap<Activity, ActivityDTO>()
.ForMember(dst => dst.OwnerId, src => src.MapFrom(ol => ol.User.Id))
.ForMember(dst => dst.OwnerName, src => src.MapFrom(ol => ol.User.FirstName + " " + ol.User.LastName))
.ForMember(dst => dst.CategoryName, src => src.MapFrom(ol => ol.Category.Name));
CreateMap<ActivityDTO, Activity>()
.ForMember(dst => dst.UserId, opt => opt.MapFrom(src => HttpContext.Current.User.Identity.GetUserId()));
}
public static void Run()
{
AutoMapper.Mapper.Initialize(a =>
{
a.AddProfile<AutomapperWebProfile>();
});
}
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AutomapperWebProfile.Run();
GlobalConfiguration.Configuration.Formatters
.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters
.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
}
public class ClientMappingProfile : Profile
{
public ClientMappingProfile()
{
CreateMap<Activity, ActivityDTO>()
.ForMember(dst => dst.OwnerId, src => src.MapFrom(ol => ol.User.Id))
.ForMember(dst => dst.OwnerName, src => src.MapFrom(ol => ol.User.FirstName + " " + ol.User.LastName))
.ForMember(dst => dst.CategoryName, src => src.MapFrom(ol => ol.Category.Name));
CreateMap<ActivityDTO, Activity>()
.ForMember(dst => dst.UserId, opt => opt.MapFrom(src => HttpContext.Current.User.Identity.GetUserId()));
}
}
public class AutoMapperConfig
{
public MapperConfiguration Configure()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<ClientMappingProfile>();
});
return config;
}
}
public class ActivitiesController : ApiController
{
private ApplicationDbContext db = new ApplicationDbContext();
....
[HttpGet]
[Route("api/v1/Activities/{sortfields=Id}/{pagenumber=1}/{pagesize=10}", Name="GetActivities")]
[CacheOutput(ClientTimeSpan = 60, ServerTimeSpan = 60)]
public async Task<IHttpActionResult> GetActivities(string sortfields, int pageNumber, int pageSize)
{
var config = new AutoMapperConfig().Configure();
...
var activitiesDTO = await (db.Activities
.Include(b => b.User)
.Include(c => c.Category)
.Where(q => q.UserId == userId)
.ProjectTo< ActivityDTO>(config)
.AsQueryable()
.ApplySort(sortfields)
.Skip((pageNumber - 1) * pageSize).Take(pageSize)).ToListAsync();
....
return Ok(Data)
}
}
在进一步研究之后,我提出了这种方法,与我之前所做的类似,但它更适用于任何人: AutomapperConfig.cs:
private MapperConfiguration configuration = new MapperConfiguration(cfg => {
cfg.CreateMap<Activity, ActivityDTO>()
.ForMember(dst => dst.OwnerId, src => src.MapFrom(ol => ol.User.Id))
.ForMember(dst => dst.OwnerName, src => src.MapFrom(ol => ol.User.FirstName + " " + ol.User.LastName))
.ForMember(dst => dst.CategoryName, src => src.MapFrom(ol => ol.Category.Name));
cfg.CreateMap<ActivityDTO, Activity>()
.ForMember(dst => dst.UserId, opt => opt.MapFrom(src => HttpContext.Current.User.Identity.GetUserId()));
});
var activitiesDTO = await (db.Activities
.Include(b => b.User)
.Include(c => c.Category)
.Where(q => q.UserId == userId)
.ProjectTo< ActivityDTO>(configuration)
.AsQueryable()
.ApplySort(sortfields)
.Skip((pageNumber - 1) * pageSize).Take(pageSize)).ToListAsync();
public class AutomapperWebProfile : AutoMapper.Profile
{
public AutomapperWebProfile()
{
CreateMap<Activity, ActivityDTO>()
.ForMember(dst => dst.OwnerId, src => src.MapFrom(ol => ol.User.Id))
.ForMember(dst => dst.OwnerName, src => src.MapFrom(ol => ol.User.FirstName + " " + ol.User.LastName))
.ForMember(dst => dst.CategoryName, src => src.MapFrom(ol => ol.Category.Name));
CreateMap<ActivityDTO, Activity>()
.ForMember(dst => dst.UserId, opt => opt.MapFrom(src => HttpContext.Current.User.Identity.GetUserId()));
}
public static void Run()
{
AutoMapper.Mapper.Initialize(a =>
{
a.AddProfile<AutomapperWebProfile>();
});
}
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AutomapperWebProfile.Run();
GlobalConfiguration.Configuration.Formatters
.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters
.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
}
public class ClientMappingProfile : Profile
{
public ClientMappingProfile()
{
CreateMap<Activity, ActivityDTO>()
.ForMember(dst => dst.OwnerId, src => src.MapFrom(ol => ol.User.Id))
.ForMember(dst => dst.OwnerName, src => src.MapFrom(ol => ol.User.FirstName + " " + ol.User.LastName))
.ForMember(dst => dst.CategoryName, src => src.MapFrom(ol => ol.Category.Name));
CreateMap<ActivityDTO, Activity>()
.ForMember(dst => dst.UserId, opt => opt.MapFrom(src => HttpContext.Current.User.Identity.GetUserId()));
}
}
public class AutoMapperConfig
{
public MapperConfiguration Configure()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<ClientMappingProfile>();
});
return config;
}
}
public class ActivitiesController : ApiController
{
private ApplicationDbContext db = new ApplicationDbContext();
....
[HttpGet]
[Route("api/v1/Activities/{sortfields=Id}/{pagenumber=1}/{pagesize=10}", Name="GetActivities")]
[CacheOutput(ClientTimeSpan = 60, ServerTimeSpan = 60)]
public async Task<IHttpActionResult> GetActivities(string sortfields, int pageNumber, int pageSize)
{
var config = new AutoMapperConfig().Configure();
...
var activitiesDTO = await (db.Activities
.Include(b => b.User)
.Include(c => c.Category)
.Where(q => q.UserId == userId)
.ProjectTo< ActivityDTO>(config)
.AsQueryable()
.ApplySort(sortfields)
.Skip((pageNumber - 1) * pageSize).Take(pageSize)).ToListAsync();
....
return Ok(Data)
}
}
public类ClientMappingProfile:Profile
{
公共客户端映射配置文件()
{
CreateMap()
.FormMember(dst=>dst.OwnerId,src=>src.MapFrom(ol=>ol.User.Id))
.FormMember(dst=>dst.OwnerName,src=>src.MapFrom(ol=>ol.User.FirstName+“”+ol.User.LastName))
.ForMember(dst=>dst.CategoryName,src=>src.MapFrom(ol=>ol.Category.Name));
CreateMap()
.ForMember(dst=>dst.UserId,opt=>opt.MapFrom(src=>HttpContext.Current.User.Identity.GetUserId());
}
}
公共类自动映射配置
{
公共MapperConfiguration配置()
{
var config=new-MapperConfiguration(cfg=>
{
AddProfile();
});
返回配置;
}
}
XXXController.cs:
private MapperConfiguration configuration = new MapperConfiguration(cfg => {
cfg.CreateMap<Activity, ActivityDTO>()
.ForMember(dst => dst.OwnerId, src => src.MapFrom(ol => ol.User.Id))
.ForMember(dst => dst.OwnerName, src => src.MapFrom(ol => ol.User.FirstName + " " + ol.User.LastName))
.ForMember(dst => dst.CategoryName, src => src.MapFrom(ol => ol.Category.Name));
cfg.CreateMap<ActivityDTO, Activity>()
.ForMember(dst => dst.UserId, opt => opt.MapFrom(src => HttpContext.Current.User.Identity.GetUserId()));
});
var activitiesDTO = await (db.Activities
.Include(b => b.User)
.Include(c => c.Category)
.Where(q => q.UserId == userId)
.ProjectTo< ActivityDTO>(configuration)
.AsQueryable()
.ApplySort(sortfields)
.Skip((pageNumber - 1) * pageSize).Take(pageSize)).ToListAsync();
public class AutomapperWebProfile : AutoMapper.Profile
{
public AutomapperWebProfile()
{
CreateMap<Activity, ActivityDTO>()
.ForMember(dst => dst.OwnerId, src => src.MapFrom(ol => ol.User.Id))
.ForMember(dst => dst.OwnerName, src => src.MapFrom(ol => ol.User.FirstName + " " + ol.User.LastName))
.ForMember(dst => dst.CategoryName, src => src.MapFrom(ol => ol.Category.Name));
CreateMap<ActivityDTO, Activity>()
.ForMember(dst => dst.UserId, opt => opt.MapFrom(src => HttpContext.Current.User.Identity.GetUserId()));
}
public static void Run()
{
AutoMapper.Mapper.Initialize(a =>
{
a.AddProfile<AutomapperWebProfile>();
});
}
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AutomapperWebProfile.Run();
GlobalConfiguration.Configuration.Formatters
.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters
.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
}
public class ClientMappingProfile : Profile
{
public ClientMappingProfile()
{
CreateMap<Activity, ActivityDTO>()
.ForMember(dst => dst.OwnerId, src => src.MapFrom(ol => ol.User.Id))
.ForMember(dst => dst.OwnerName, src => src.MapFrom(ol => ol.User.FirstName + " " + ol.User.LastName))
.ForMember(dst => dst.CategoryName, src => src.MapFrom(ol => ol.Category.Name));
CreateMap<ActivityDTO, Activity>()
.ForMember(dst => dst.UserId, opt => opt.MapFrom(src => HttpContext.Current.User.Identity.GetUserId()));
}
}
public class AutoMapperConfig
{
public MapperConfiguration Configure()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<ClientMappingProfile>();
});
return config;
}
}
public class ActivitiesController : ApiController
{
private ApplicationDbContext db = new ApplicationDbContext();
....
[HttpGet]
[Route("api/v1/Activities/{sortfields=Id}/{pagenumber=1}/{pagesize=10}", Name="GetActivities")]
[CacheOutput(ClientTimeSpan = 60, ServerTimeSpan = 60)]
public async Task<IHttpActionResult> GetActivities(string sortfields, int pageNumber, int pageSize)
{
var config = new AutoMapperConfig().Configure();
...
var activitiesDTO = await (db.Activities
.Include(b => b.User)
.Include(c => c.Category)
.Where(q => q.UserId == userId)
.ProjectTo< ActivityDTO>(config)
.AsQueryable()
.ApplySort(sortfields)
.Skip((pageNumber - 1) * pageSize).Take(pageSize)).ToListAsync();
....
return Ok(Data)
}
}
公共类活动控制器:ApiController
{
私有ApplicationDbContext db=新ApplicationDbContext();
....
[HttpGet]
[路由(“api/v1/Activities/{sortfields=Id}/{pagenumber=1}/{pagesize=10}”,Name=“GetActivities”)]
[CacheOutput(ClientTimeSpan=60,ServerTimeSpan=60)]
公共异步任务GetActivities(字符串sortfields、int pageNumber、int pageSize)
{
var config=new AutoMapperConfig().Configure();
...
var activitiesDTO=await(db.Activities
.Include(b=>b.User)
.包括(c=>c.类别)
.Where(q=>q.UserId==UserId)
.ProjectTo(配置)
.AsQueryable()
.ApplySort(sortfields)
.Skip((pageNumber-1)*pageSize.Take(pageSize)).toListSync();
....
返回Ok(数据)
}
}
我可能会移动var config=new AutoMapperConfig().Configure()将>编码到暴露于任何方法的私有属性中
有人在使用这种方法吗?我看到一些人通过Global.asax进行配置,比如我尝试失败(原始问题)。同样,我也不确定这种方法是否是一种旧的解决方案
你的想法 通常情况下,您会有一个DI容器,可以为启动进行配置。然后通过控制器的构造函数参数获得配置或映射器实例。在没有DI容器的情况下,您可以在控制器构造函数中实例化映射器——是的,每个需要它的控制器。