.NET Core 2.0 Web 中的 BSON API

BSON in .NET Core 2.0 Web API

我有 .NET Core WebApi 项目,我想在 BSON 中发送请求并获得响应。

我安装了WebApiContrib.Core.Formatter.Bson并添加了

services.AddMvc().AddBsonSerializerFormatters(); 

Startup.csConfigureServices.

我还需要做其他事情吗?

我在控制器中有测试方法:

[HttpGet]
public string GetTestBson()
{
    return "test string bson";
}

我尝试使用 Postman 对其进行测试,在 headers 我有 Content-Type: application/bson 但作为回应我没有BSON ...我有"test string bson"

我做错了什么?

在发出请求时,您需要设置一个 请求 header of Accept 设置为 application/bson:

Accept: application/bson

通过使用 Content-Type: application/bson,你实际上是在说你发送的请求 body 是 BSON,但由于这是一个 GET 请求,你实际上并没有发送 body 完全没有。使用 Accept: application/bson 表示您希望 BSON 在响应中被 returned。

StackExchange 网站管理员的 answer 更详细地解释了 AcceptContent-Type 之间的区别。

除了此处需要的 Accept header 之外,您还需要 return 来自您的操作的 object 或数组,否则BSON 序列化器将失败并显示如下消息:

Error writing String value. BSON must start with an Object or Array. Path ''.

为了return一个object,你可以这样做:

[HttpGet]
public IActionResult GetTestBson()
{
    return Ok(new { Value = "test string bson" });
}

这个 return 是一个新的匿名类型,属性 为 Value - 你不能只 return 你现有的 string 作为 object,作为 BSON object 必须具有属性。