Skip to content

Multipart body length limit 16384 exceeded in NET CORE #50252

Closed
@mohpais

Description

@mohpais

What I am trying to do

I'm trying to access the API in my project (NET Core 6 WebApi) to get data from the response for the project purpose. The API response that I will access is XML data which consists of some data such as title, description, creation date, and also photo data in it.

Here's how I access the API using IHttpClientFactory in mycontroller:

[Route("Get")]
[HttpGet]
public async Task<IActionResult> Get()
{
   HttpResponseMessage response = await _httpClient.GetAsync('the_name_of_the_api_i_will_be_accessing');
   if (response.IsSuccessStatusCode)
   {
      // Check if the response is multipart/mixed
      var headers = response.Content.Headers;
      if (headers.ContentType?.MediaType == "multipart/mixed")
      {
         // Get the boundary from the content type header
         string boundary = headers.ContentType.Parameters.FirstOrDefault(p => p.Name == "boundary")?.Value ?? "";
         if (string.IsNullOrWhiteSpace(boundary) || (boundary.Length > new FormOptions().MultipartBoundaryLengthLimit))
         {
            throw new InvalidDataException("Boundary is missing or too long.");
         }
         Stream contentStream = await response.Content.ReadAsStreamAsync();
         // Create a new reader based on the boundary
         var reader = new MultipartReader(boundary, contentStream);

         // Start reading sections from the MultipartReader until there are no more
         var section = await reader.ReadNextSectionAsync();
         while (section != null)
         {
            // Check the content type of each section
            var contentType = new ContentType(section.ContentType);
            // Read and process the content of each section based on its content type
            if (contentType.MediaType == "application/xml")
            {
               // This section contains XML data, you can parse and process it as needed
               var xmlContent = await section.ReadAsStringAsync();
               // Process the XML content
            }
            else if (contentType.MediaType == "image/jpeg")
            {
               // This section contains an image (binary data), so i can save it or process it as needed
               using (var imageStream = File.Create("path/to/save/image.jpg"))
               {
                  await section.Body.CopyToAsync(imageStream);
               }
            }
            // Read the next section
            section = await reader.ReadNextSectionAsync();
         }
      }
      return Ok();
   }
   else
   {
      return StatusCode((int)response.StatusCode, "API request failed");
   }
}

However, when I try to read section from the MultipartReader in code:

var section = await reader.ReadNextSectionAsync();

I got an Error like this

System.IO.InvalidDataException: Multipart body length limit 16384 exceeded.

Things i've tried:

I've tried several ways to overcome this, one of which is to increase the MultipartBodyLengthLimit in Program.cs

services.Configure<FormOptions>(options =>
{
  options.MultipartBodyLengthLimit = 104857600; // Set to a higher value for the body
});

and I still get the same error

Postman response

In postman, it will return XML data and provides information with content-type multipart/mixed.

Here is the response result in postman:

<?xml version="1.0" encoding="utf-8"?>
<EventNotificationAlert version="2.0" xmlns="http://www.isapi.org/ver20/XMLSchema">
<dateTime>2023-08-22T09:47:30.486+07:00</dateTime>
<eventState>active</eventState>
<eventDescription>ANPR</eventDescription>
...
</EventNotificationAlert>
-----------------------------7daf10c20d06
Content-Disposition: form-data; name="detectionPicture"; filename="detectionPicture.jpg"
Content-Type: image/jpeg
Content-Length: 548804

How to solve this problem?

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-networkingIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions

    Type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions