NET CORE 超出多部分主体长度限制 16384

问题描述 投票:0回答:1

我正在尝试做的事情:

我正在尝试访问我的项目中的 API (NET Core 6 WebApi),以从响应中获取数据以用于项目目的。我将访问的 API 响应是 XML 数据,其中包含一些数据,例如标题、描述、创建日期以及其中的照片数据。但我收到错误 Multipart body length limit 16384超出NET CORE。

以下是我如何在我的控制器中使用 IHttpClientFactory 访问 API:

[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");
   }
}

来自 API 的 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

我尝试过的事情:

实际上在这个链接上InvalidDataException:超出了多部分主体长度限制16384几乎与我的相同,但区别在于我们使用的NET Core的版本和Content-Type响应,这是我在API中的Content-Type将以multipart/mixed的形式访问。

该链接中解决的几个问题是:

  • 在 Watch 或调试快速视图中跳过视图 Request.From [不适用于我]
  • 增加 BodyLengthLimit [对我不起作用]
var builder = WebApplication.CreateBuilder(args);
{
    var services = builder.Services;
    var configuration = builder.Configuration;
    ...

    services.Configure<FormOptions>(x =>
    {
        x.MultipartHeadersLengthLimit = Int32.MaxValue;
        x.MultipartBoundaryLengthLimit = Int32.MaxValue;
        x.MultipartBodyLengthLimit = Int64.MaxValue;
        x.ValueLengthLimit = Int32.MaxValue;
        x.BufferBodyLengthLimit = Int64.MaxValue;
        x.MemoryBufferThreshold = Int32.MaxValue;
    });
}
  • 将 http 更改为 https 或通过删除 Startup.cs 中的 app.UseHttpsRedirection() 来使用 http(已检查答案)[遗憾的是,对我不起作用]

希望这是足够的信息。如果没有,请告诉我您需要什么,我很乐意提供或测试任何建议。

c# asp.net-core xmlhttprequest asp.net-core-6.0
1个回答
0
投票

使用 ReadAsStreamAsync() 函数在我的情况下不起作用,因此我使用了另一种方法,即使用 ReadAsByteArrayAsync() 函数将 Content-Type: multipart 的每个部分读取为字节,然后努力处理字节,因为之前不太懂字节计算。但如果结果符合预期,那并不重要。

给和我有同样问题的人一个注释,如果回复 来自您的多部分是文件数据,不要转换它 成一个字符串,这样你就可以将每个部分分开,尽管这种方式会 是工作,每个部分仍然可以使用边界分开,但是 响应中的数据文件将被损坏,因为它是 转换为字符串并且变得不可读,所以解决方案是将其转换为字节

© www.soinside.com 2019 - 2024. All rights reserved.