我有 .NET Core WebApi 项目,我想在 BSON 中发送请求并获得响应。
我安装了 WebApiContrib.Core.Formatter.Bson
并添加了
services.AddMvc().AddBsonSerializerFormatters();
Startup.cs 中的 ConfigureServices
。
我还需要做其他事情吗?
我在 Controller 中有测试方法:
[HttpGet]
public string GetTestBson()
{
return "test string bson";
}
我尝试使用 Postman 对其进行测试,在 header 中我有 Content-Type: application/bson
但作为回应,我没有 BSON...我有 "test string bson"
我做错了什么?
最佳答案
在发出请求时,您需要设置 Accept
的 request header ,该 header 设置为 application/bson
:
Accept: application/bson
通过使用 Content-Type: application/bson
,您实际上是在说您发送的请求正文是 BSON,但由于这是一个 GET 请求,您实际上并没有发送一具尸体。使用 Accept: application/bson
表示您希望在响应中返回 BSON。
这answer StackExchange 的 WebMasters 更详细地解释了 Accept
和 Content-Type
之间的区别。
除了此处需要的 Accept
header 外,您还需要从操作中返回一个对象或数组,否则 BSON 序列化程序将失败并显示如下消息:
Error writing String value. BSON must start with an Object or Array. Path ''.
为了返回一个对象,你可以这样做:
[HttpGet]
public IActionResult GetTestBson()
{
return Ok(new { Value = "test string bson" });
}
这将返回一个新的匿名类型,其属性为 Value
- 您不能只将现有的 string
作为 object
返回,因为BSON 对象必须具有属性。
关于c# - .NET Core 2.0 Web API 中的 BSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52757660/