c# - .NET Core 2.0 Web API 中的 BSON

标签 c# asp.net-web-api asp.net-core postman bson

我有 .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"

我做错了什么?

最佳答案

在发出请求时,您需要设置 Acceptrequest header ,该 header 设置为 application/bson:

Accept: application/bson

通过使用 Content-Type: application/bson,您实际上是在说您发送的请求正文是 BSON,但由于这是一个 GET 请求,您实际上并没有发送一具尸体。使用 Accept: application/bson 表示您希望在响应中返回 BSON。

answer StackExchange 的 WebMasters 更详细地解释了 AcceptContent-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/

相关文章:

c# - 在 C# 中将 Aes.Key 转换为 SecureString

c# - 禁用点击按钮事件c#

C#对象引用问题

c# - Xamarin 中的蓝牙打印

visual-studio - ASP.NET Core 2 上未定义 runco​​mmand 属性

http - HTTP GET错误用户无效

asp.net-mvc - 如何从 MVC 调用 Web API 无延迟?

c# - 在 RESTful Web Api 方法中检索委托(delegate)人

c# - 在 C# 中加速将复杂类型转换为另一种复杂类型以进行序列化

c# - 带有EF Core Linq2Sql的聚合的聚合