Search code examples
c#asp.net-web-apiasp.net-corepostmanbson

BSON in .NET Core 2.0 Web API


I have .NET Core WebApi project and I would like send request and get response in BSON.

I installed WebApiContrib.Core.Formatter.Bson and added

services.AddMvc().AddBsonSerializerFormatters(); 

in Startup.cs in ConfigureServices.

Do I need to do anything else?

I have test method in controller:

[HttpGet]
public string GetTestBson()
{
    return "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"

What am I doing wrong?


Solution

  • When making your request, you need to set a request header of Accept that is set to application/bson:

    Accept: application/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.

    This answer over at StackExchange's WebMasters explains the difference between Accept and Content-Type in more detail.

    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:

    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" });
    }
    

    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.