top of page

Send multi-part content to an API from a .NET Core API (.NET 5.0)

Scenario — You are developing a web API that takes form data in its post method. And from that API, you need to call another API that processes this data by saving it in disc or cloud storage.


Your Web API is just an intermediate hop between the front-end and the API which actually process the data. You may encounter such a scenario when you work on integrating third-party APIs into your project.

I am going to demonstrate the intermediate API here using .NET 5.0


Final API requires multi-part content as given in the below model.

public class EmployeeUploadRequest
{
 public string Name { get; set; }
 public List<IFormFIle> Files { get; set; }
}

From Postman, request will look like this



In Controller class, your action method will look like below

[HttpPost]
[Route(“upload”)]
public async Task<ActionResult<YourResponse>> Upload([FromForm] EmployeeUploadRequest request)
{
 // call to service class goes from here
}

Service method implementation as follows. Here I am using a simple http client for making the request to the final api. You can use any packages like RestEase or Polly for better management and circuit breaking.

using (var client = new HttpClient())
{
    var content = new MultipartFormDataContent();
    content.Add(new StringContent(request.Name), “name”);
    foreach (var file in request.Files)
    {
      content.Add(new StreamContent(file.OpenReadStream())
       {
         Headers =
         {
           ContentLength = file.Length,
           ContentType = new MediaTypeHeaderValue(file.ContentType)
         }
       }, “files”, file.FileName);
     }
     var result = await client.PostAsync(endpointUrl, content);
}


Implementation with RestEase.

If you would like to use RestEase package instead of HttpClient object. You can use below code snippet.

var service = RestClient.For<IService>(endpointUrl);
var content = new MultipartFormDataContent();
content.Add(new StringContent(request.Name), “name”);
foreach (var file in request.Files)
{
      content.Add(new StreamContent(file.OpenReadStream())
       {
         Headers =
         {
           ContentLength = file.Length,
           ContentType = new MediaTypeHeaderValue(file.ContentType)
         }
       }, “files”, file.FileName);
}
var result = await service.Upload(content)

And the service interface implementation for RestEase will look like

public interface IService
{
  [AllowAnyStatusCode]
  [Header(“Content-Disposition”, “form-data”)]
  [Post]
  Task<Response<YourResponse>> Upload(
                 [Body]MultipartFormDataContent content);
}


Source: Medium ; Riteklick


The Tech Platform

0 comments
bottom of page