Search code examples
asp.net-corebson

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


I'm new to ASP.NET Core and network programming in general. I've just successfully completed my first ASP.NET Core Web API based on RESTfull design principles. It's currently using JSON serialization to send out the responses (the Visual Studio default) but I'd like to try BSON. I've spent the day googling and I can't seem to find any examples of how to add BSON serialization/deserialization capability to the server. I've come across several articles on how to do this on full-framework ASP.NET, where it's been included out-of-the-box for several years (for example: https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/bson-support-in-web-api-21 and http://www.strathweb.com/2012/07/bson-binary-json-and-how-your-web-api-can-be-even-faster/) but nothing pertaining to ASP.NET Core specifically.

I've hunted through the source code files generated by VS hoping to find something similar to the full-framework examples I've linked but nothing jumped out at me as there were few similarities. Could someone please post (or link to) some code that shows how this is done in ASP.NET Core? Thank you very much in advance.


Solution

  • You can use this formatter: https://github.com/WebApiContrib/WebAPIContrib.Core

    Then add at startup.cs:

    using WebApiContrib.Core.Formatter.Bson;
    
    namespace MyApp
    {
        public class Startup
        {
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc()
                    .AddBsonSerializerFormatters();
            }
        }
    }