【问题标题】:BSON in .NET Core 2.0 Web API.NET Core 2.0 Web API 中的 BSON
【发布时间】:2019-03-16 09:27:54
【问题描述】:

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

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

services.AddMvc().AddBsonSerializerFormatters(); 

Startup.csConfigureServices

我还需要做什么吗?

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

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

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

我做错了什么?

【问题讨论】:

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


    【解决方案1】:

    发出请求时,您需要设置Acceptrequest 标头,该标头设置为application/bson

    Accept: application/bson
    

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

    StackExchange 的 WebMasters 上的 answer 更详细地解释了 AcceptContent-Type 之间的区别。

    除了此处需要 Accept 标头外,您还需要从操作中返回对象或数组,否则 BSON 序列化程序将失败并显示如下消息:

    写入字符串值时出错。 BSON 必须以对象或数组开头。路径''。

    为了返回一个对象,你可以这样做:

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

    这将返回一个新的匿名类型,其属性为 Value - 您不能只将现有的 string 作为 object 返回,因为 BSON 对象必须具有属性。

    【讨论】:

    • 太棒了!现在我在邮递员身上看到类似“....test....string....bson....”的东西,我认为可以吗?但是我可以获取十六进制值来检查它是否可以反过来工作吗?
    • 您也许可以使用 this 之类的东西从 JSON 转换为 BSON 以进行测试。
    猜你喜欢
    • 2018-03-26
    • 2018-05-16
    • 1970-01-01
    • 2018-03-12
    • 2018-09-16
    • 2023-03-09
    • 2019-01-12
    • 2018-05-08
    • 2018-04-16
    相关资源
    最近更新 更多