Skip to content

Instantly share code, notes, and snippets.

@JimmyPun610
Last active September 18, 2020 11:37
Show Gist options
  • Save JimmyPun610/e27856c23a1b39f56d6fedec1a622f71 to your computer and use it in GitHub Desktop.
Save JimmyPun610/e27856c23a1b39f56d6fedec1a622f71 to your computer and use it in GitHub Desktop.
Package installation
Install-Package WebApiContrib.Core.Formatter.Bson -Version 2.1.0
Server side
  1. AllowSynchronousIO (optional)
//In Startup.cs
    public void ConfigureServices(IServiceCollection services)
{
    services.Configure<KestrelServerOptions>(options =>
    {
        options.AllowSynchronousIO = true;
    });

    // If using IIS:
    services.Configure<IISServerOptions>(options =>
    {
        options.AllowSynchronousIO = true;
    });

    // other services
}
  1. Setup in Startup.cs
 using WebApiContrib.Core.Formatter.Bson;
 
 
 public void ConfigureServices(IServiceCollection services){
   ....
   services.AddControllers().AddBsonSerializerFormatters();       
   ....
 }
  1. Setup API
 public async Task<IActionResult> UploadFile(UploadFileRequest request)
 {
     //Implementation
     return Ok();
 }
  1. Client Side prepare Bson ByteArray
  //Convert the request to ByteArrayContent in Bson
  public static ByteArrayContent ToBsonByteArrayContent<T>(this T obj)
  {
      if (obj == null)
      {
          return null;
      }

      using(MemoryStream ms = new MemoryStream())
      {
          using (BsonDataWriter datawriter = new BsonDataWriter(ms))
          {
              JsonSerializer serializer = new JsonSerializer();
              serializer.Serialize(datawriter, obj);
              byte[] sa = ms.ToArray();
              var content = new ByteArrayContent(ms.ToArray());
              content.Headers.ContentType = new MediaTypeHeaderValue("application/bson");
              return content;
          }
      }
  }
  1. Client Side Send Request
   HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post, url);
   HttpResponseMessage httpResponse  = await httpClient.PostAsync(url, request.ToBsonByteArrayContent());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment