.NET Framework 4.5.2,.Asp.NET Web API 5.2.3,AutoMapper 5.1.1
我在AddressController上有以下ASP.NET MVC WebApi Action Method。对于我的测试,我只返回10条记录,如下面的服务方法所示:
[Route("api/Address/GetAllAsync")]
[HttpGet]
public async Task<IEnumerable<AddressModel>> GetAllAsync()
{
AddressService service = new AddressService(new DataContext());
Task<IEnumerable<Address>> data = service.GetAllAddressesAsync();
var addressList = Mapper.Map<Task<IEnumerable<Address>>, Task<IEnumerable<AddressModel>>>(data);
return await addressList;
}
service.GetAllAddressesAsync是
public async Task<IEnumerable<Address>> GetAlladdressesAsync()
{
var data = from a in _context.Addresses.Take(10)
orderby a.City
select a;
return await data.ToListAsync();
}
AutoMapper在Global.asax.cs中配置为:
Mapper.Initialize(cfg => cfg.CreateMap<Address, AddressModel>());
Mapper.AssertConfigurationIsValid();
我还尝试配置AutoMapper,如
Mapper.Initialize(cfg => cfg.CreateMap<Task<IEnumerable<Address>>, Task<IEnumerable<AddressModel>>>());
Mapper.AssertConfigurationIsValid();
使用第一个配置解决方案启动,但是当从浏览器调用GetAllAsync()方法时,响应主体(在F12开发人员工具/网络中)显示以下错误消息:
{“message”:“发生错误。”,“exceptionMessage”:“缺少类型映射配置或不支持的映射。\ r \ n \ r \ nMapping类型:\ r \ nTask 1 -> Task
1 \ r \ nSystem.Threading.Tasks.Task 1[[System.Collections.Generic.IEnumerable
1 [[DataAccess.Address,DataAccess,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]],mscorlib,Version = 4.0.0.0,Culture = neutral ,PublicKeyToken = b77a5c561934e089]] - &gt; System.Threading.Tasks.Task 1[[System.Collections.Generic.IEnumerable
1 [[TestAspNetIdentity.Models.AddressModel,TestAspNetIdentity,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]],mscorlib, Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]“,”exceptionType“:”AutoMapper.AutoMapperMappingException“,”stackTrace“:”
当尝试AutoMapper的第二个配置时,解决方案会启动但是在调用方法时,请求会在客户端或服务器上没有任何响应或异常而死亡,并且浏览器会在无限循环中等待响应。
如何配置和使用AutoMapper将Task<IEnumerable<MyTypeA>>
映射到Task<IEnumerable<MyTypeB>>
?我是否使用async-task-awayt使用了一些基本错误?有人有例子吗?
谢谢你的帮助。
此致 阿德里安
答案 0 :(得分:4)
您不应该尝试映射任务 - 等待任务的结果并映射:
D 2
E 2
F 2
H 17
M 3
N 1
S 1
---
F 3
L 18
W 7
---
A 1
D 1
S 3
T 23
---
此外,映射时无需指定源类型。