您好我最近发现我可以构建一个请求类,这样在控制器参数中我不需要有多个[FromHeader]参数和一个[FromBody]参数。相反,我在下面创建了一个类RequestForController。目前,要将请求类转换为实体类,我需要创建一个指定目标和源的所有成员的映射。如果合同/实体发生变化,那么我需要在两个类以及automapper配置中更改它。我的目标是配置automapper,以便在合同/实体更改时不需要维护automapper配置。我在下面发布了我的设置示例
// Source class Body Members
public class RequestBody
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
// Source class Headers
public class RequestHeaders
{
[FromHeader]
public string SomeHeader { get; set; }
}
// Source Class
public class RequestForController
{
public RequestHeaders Headers { get; set; }
[FromBody, Required(ErrorMessage = "Request Body is missing")]
public RequestBody Body { get; set; }
}
// Destination class
public class EntityModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string SomeHeader { get; set; }
}
// AutoMapper Configuration in Startup.cs
CreateMap<RequestForController, EntityModel>()
.ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.Body.FirstName))
.ForMember(dest => dest.LastName, opt => opt.MapFrom(src => src.Body.LastName))
.ForMember(dest => dest.SomeHeader, opt => opt.MapFrom(src => src.Headers.SomeHeader));
// Controller Function
public async Task<IActionResult> ApiEndpoint(RequestForController request)
{
// do validation
var entity = Mapper.Map<EntityModel>(request);
// do work
return Ok();
}