使用自动映射器从动态到具体类型

dynamic to concrete type with automapper

我在主体中的 WebApi 控制器上使用匿名类型做了一个 post 我有这个 new { Firstname = "AA", Lastname = "BB"}

[HttpPost]
public IHttpActionResult Post([FromBody]dynamic person)
{
}

当我点击控制器时,person 不为空,我可以看到属性及其数据。

在控制器中,我想将 dynamic 类型转换为我的具体类型 Person

public class Person
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

我试过 Mapper.Initialize(cfg => cfg.CreateMap<dynamic, Person>());

当我这样做时

var person = Mapper.Map<dynamic, Person>(source);

person的所有属性都是null

有什么想法吗?

谢谢,

根据 documentation,而不是...

    var person = Mapper.Map<dynamic, Person>(source);

...只需使用...

    var person = Mapper.Map<Person>(source);

完整示例:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public override string ToString() { return FirstName + " " + LastName; }
}

//Main
Mapper.Initialize( cfg => {} );
dynamic source = new ExpandoObject();
source.FirstName = "Hello";
source.LastName = "World";
var person = Mapper.Map<Person>(source);

Console.WriteLine("GetType()= '{0}' ToString()= '{1}'", person.GetType().Name, person);

输出:

GetType()= 'Person' ToString()= 'Hello World'

Link to DotNetFiddle demo