How to return BSON from asp.net core 5 controller

Viewed 496

I want to return BSON from a controller so that I can compare performance differences with returning normal JSON. I can't find any details on doing this specifically in asp.net Core 5. All I can find are articles that refer to doing this in previous versions of .Net core, associated with Mongo, or older webapi versions.

This How do I enable BSON serialization in my ASP.NET Core Web API?

and this How do I configure Web API .Net core to accept Binary JSON?

say that it isn't available ootb and needs https://github.com/WebApiContrib/WebAPIContrib.Core.

This BSON in .NET Core 2.0 Web API says a similar thing but also advises on how to call it.

Whilst they are earlier versions of .Net Core, I have tried this in my asp.net core 5 project. I don't have the AddMvc call since it is not required, however the WebAPIContrib package does make available the same method for Controllers, so I have the following in my ConfigureServices method:

services.AddControllers().AddBsonSerializerFormatters();

The test api method is super simple:

[HttpGet]
[Route("api/GetList")]
public List<string> GetList()
{
    return new List<string>() { "Item1", "Item2", "Item3", "Item4"};           
}

In the calling project, this works just fine when returning JSON. However if I add the following media type into the request:

request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));

Then the caller gets a 500 Internal server error. The code in the GetList() server method is executing and returning, but clearly something in asp.net core is not working to format the output as BSON.

What am I missing or doing wrong here? How can I enable BSON in a simple web api project in .net 5?

0 Answers
Related