在 ASP.NET Core 中发布复杂类型

dan*_*001 5 c# rest asp.net-core

我在使用 .Net Core 开发 Restful webapi 时遇到问题,我无法使用 HTTP POST 方法来插入复杂类型对象而不将参数指定为“FromBody”。根据 Microsoft 的文档...

ASP.NET Web API 中的参数绑定

在 HTTP POST 上使用复杂类型时,我不必指定[FromBody]数据注释,它应该可以正常工作,但是当我尝试使用 webapi 中的方法时...

// POST api/checker/
[HttpPost]
public int Insert(Entity e)
{
    Console.WriteLine($"Entity: {e.ID} - {e.Name}");
}
Run Code Online (Sandbox Code Playgroud)

其中实体有一个 id 和一个名称,使用这个客户端方法......

string json = JsonConvert.SerializeObject(entity);        
HttpClient client = new HttpClient();            
HttpResponseMessage message         = await client.PostAsync(
        "http://localhost:5000/api/checker", 
        new StringContent(json, Encoding.UTF8, "application/json"));
Run Code Online (Sandbox Code Playgroud)

该对象以 0(ID)和 null值到达 webapi (name),除非 webapi 方法签名使用[FromBody]注释。我在这里错过了什么吗?我已经做了一个研究,无法弄清楚这一点。

更新:

这是我的实体类:

public class Entity
{
    public int ID { get; set; }
    public bool IsDeleted { get; set; }
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是使用 Newtonsoft 的 JSON.NET 序列化的 json:

{"ID":99,"IsDeleted":false,"Name":"TestChecker"}
Run Code Online (Sandbox Code Playgroud)

这是插入 web api 方法的输出:

Entity: 0
Run Code Online (Sandbox Code Playgroud)

dee*_* zg 5

随着 MVC 和 Web Api 控制器合并在一起,asp.net core 与以前的版本进行了拆分/更改。

asp.net core 中的默认行为,对于 POST 请求,它将使用表单数据 (x-www-form-urlencoded) 查找请求正文中的数据。如果你想从 body json 中找到 application/json ,你必须明确。

此链接可能会帮助您了解详细信息: https://andrewlock.net/model-binding-json-posts-in-asp-net-core/