【问题标题】:Posting complex type in ASP.NET Core在 ASP.NET Core 中发布复杂类型
【发布时间】:2018-01-04 15:42:24
【问题描述】:

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

Parameter Binding in ASP.NET Web API

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

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

实体有一个 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"));

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

更新:

这是我的实体类:

public class Entity
{
    public int ID { get; set; }
    public bool IsDeleted { get; set; }
    public string Name { get; set; }
}

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

{"ID":99,"IsDeleted":false,"Name":"TestChecker"}

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

Entity: 0

【问题讨论】:

  • 所以您知道[FromBody] 解决了这个问题,为什么不愿意在您的参数上使用该属性?
  • 请向我们提供json和类实体,并尝试在类方法中更正您的url
  • @Jamiec,因为如果有什么概念上的错误或者我遗漏了什么,我想了解一下,因为在官方文档中他们明确表示不需要注释
  • @Esperadoce,我已经编辑了问题以提供更多信息:)
  • 那是您应该阅读的链接:docs.microsoft.com/en-gb/aspnet/core/mvc/models/model-binding(在您的情况下,MVC 和 WebApi 在 Core 中是相同的)

标签: c# rest asp.net-core


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢!您的回答加上@LukaszMakowej 提供的this link 澄清了一切!
【解决方案2】:

我想你会发现在 .Net Core 中需要 FromBody。看 Create a Web API with ASP.NET Core... 另见:Model Binding.

【讨论】:

  • 谢谢理查德!这也很有帮助,我看了一下 Create 方法 :)
【解决方案3】:

我看到你正在使用Insert 操作,但是当你调用你的 api 时,url 是“http://localhost:5000/api/checker”再试一次这个 url “http://localhost:5000/api/checker/insert”?也许它会起作用,你不需要[FromBody]

【讨论】:

  • 我尝试使用 uri 上的插入后缀进行消费,但出现 404 - Not Found 错误,应用程序路由已配置,因此我可以基于 HTTP 进行调用(类似于出现在来自this link 的表格中,可以通过“api/products”路由调用帖子)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
  • 2016-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多