.NET Core 2.0 Web API 中的 BSON [英] BSON in .NET Core 2.0 Web API
问题描述
我有 .NET Core WebApi 项目,我想在 BSON 中发送请求并获得响应.
I have .NET Core WebApi project and I would like send request and get response in BSON.
我安装了 WebApiContrib.Core.Formatter.Bson代码>
并添加
I installed WebApiContrib.Core.Formatter.Bson
and added
services.AddMvc().AddBsonSerializerFormatters();
在 Startup.cs 中,在 ConfigureServices
中.
我还需要做什么吗?
我在控制器中有测试方法:
I have test method in controller:
[HttpGet]
public string GetTestBson()
{
return "test string bson";
}
我尝试使用 Postman 对其进行测试,在标题中我有 Content-Type: application/bson
但作为回应,我没有 BSON...我有 "test string bson"
I try to test it using Postman, in headers I have Content-Type: application/bson
but in response I don't have BSON... I have "test string bson"
我做错了什么?
推荐答案
在提出请求时,您需要设置 Accept
的 request 标头,该标头设置为 <代码>应用程序/bson:
When making your request, you need to set a request header of Accept
that is set to application/bson
:
Accept: application/bson
通过使用 Content-Type: application/bson
,您实际上是在说您发送的请求正文是 BSON,但由于这是一个 GET 请求,您实际上并未发送一个身体.使用 Accept: application/bson
表示您希望在响应中返回 BSON.
By using Content-Type: application/bson
, you're effectively saying that the request body you're sending is BSON, but as this is a GET request, you're not actually sending a body at all. Using Accept: application/bson
says that you want BSON to be returned in the response.
这个答案在 StackExchange 的网站管理员更详细地解释了 Accept
和 Content-Type
之间的区别.
This answer over at StackExchange's WebMasters explains the difference between Accept
and Content-Type
in more detail.
除了此处需要的 Accept
标头之外,您还需要从您的操作中返回一个对象或一个数组,否则 BSON 序列化程序将失败并显示如下消息:
As well as the Accept
header being required here, you'll also need to return either an object or an array from your action, otherwise the BSON serialiser will fail with a message such as:
写入字符串值时出错.BSON 必须以对象或数组开头.路径''.
Error writing String value. BSON must start with an Object or Array. Path ''.
为了返回一个对象,你可以这样做:
In order to return an object, you can do something like this:
[HttpGet]
public IActionResult GetTestBson()
{
return Ok(new { Value = "test string bson" });
}
这将返回一个具有 Value
属性的新匿名类型 - 您不能将现有的 string
作为 object
返回,因为BSON 对象必须具有属性.
This returns a new anonymous type with a property of Value
- you can't just return your existing string
as an object
, as a BSON object must have properties.
这篇关于.NET Core 2.0 Web API 中的 BSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!