Install-Package WebApiContrib.Core.Formatter.Bson -Version 2.1.0
- 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
}
- Setup in Startup.cs
using WebApiContrib.Core.Formatter.Bson;
public void ConfigureServices(IServiceCollection services){
....
services.AddControllers().AddBsonSerializerFormatters();
....
}
- Setup API
public async Task<IActionResult> UploadFile(UploadFileRequest request)
{
//Implementation
return Ok();
}
- 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;
}
}
}
- Client Side Send Request
HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage httpResponse = await httpClient.PostAsync(url, request.ToBsonByteArrayContent());