- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想要做什么:
我正在尝试使用 Postman 将带有文件和 JSON blob 的 multipart/form-data
上传到 ASP.NET Core 2.2 APIController
并将文件流式传输到磁盘上的临时文件中,而不是完全放入内存中,因为这些文件的大小可能很大(20MB - 2GB)。我已经从 https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.2 的两个示例开始,从大文件示例开始,但我也尝试使用相同的错误测试小文件示例,类似但不同的堆栈跟踪。服务器使用 Kestrel。
大文件示例的堆栈跟踪(在调试器中捕获):
Exception has occurred: CLR/System.IO.InvalidDataException
Exception thrown: 'System.IO.InvalidDataException' in System.Private.CoreLib.dll: 'Multipart body length limit 16384 exceeded.'
at Microsoft.AspNetCore.WebUtilities.MultipartReaderStream.UpdatePosition(Int32 read)
at Microsoft.AspNetCore.WebUtilities.MultipartReaderStream.<ReadAsync>d__36.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Microsoft.AspNetCore.WebUtilities.StreamHelperExtensions.<DrainAsync>d__3.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.WebUtilities.MultipartReader.<ReadNextSectionAsync>d__20.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at LookupServiceAPI.Helpers.FileStreamingHelper.<StreamFile>d__1.MoveNext() in <hidden-path-to-project>\Helpers\FileStreamingHelper.cs:line 35
System.IO.InvalidDataException: Multipart body length limit 16384 exceeded.
at Microsoft.AspNetCore.WebUtilities.MultipartReaderStream.UpdatePosition(Int32 read)
at Microsoft.AspNetCore.WebUtilities.MultipartReaderStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
at Microsoft.AspNetCore.WebUtilities.StreamHelperExtensions.DrainAsync(Stream stream, ArrayPool`1 bytePool, Nullable`1 limit, CancellationToken cancellationToken)
at Microsoft.AspNetCore.WebUtilities.MultipartReader.ReadNextSectionAsync(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Http.Features.FormFeature.InnerReadFormAsync(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Mvc.ModelBinding.FormValueProviderFactory.AddValueProviderAsync(ValueProviderFactoryContext context)
at Microsoft.AspNetCore.Mvc.ModelBinding.CompositeValueProvider.CreateAsync(ActionContext actionContext, IList`1 factories)
at Microsoft.AspNetCore.Mvc.ModelBinding.CompositeValueProvider.CreateAsync(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Internal.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers;
namespace LookupServiceAPI.Helpers
{
public static class FileStreamingHelper
{
private static readonly FormOptions _defaultFormOptions = new FormOptions();
public static async Task<FormValueProvider> StreamFile(this HttpRequest request, Stream targetStream)
{
if (!MultipartRequestHelper.IsMultipartContentType(request.ContentType))
{
throw new Exception($"Expected a multipart request, but got {request.ContentType}");
}
// Used to accumulate all the form url encoded key value pairs in the
// request.
var formAccumulator = new KeyValueAccumulator();
var boundary = request.GetMultipartBoundary();
var reader = new MultipartReader(boundary, request.Body);
reader.BodyLengthLimit = Int32.MaxValue;
reader.HeadersLengthLimit = Int32.MaxValue;
var section = await reader.ReadNextSectionAsync(); //EXCEPTION HERE
while (section != null)
{
ContentDispositionHeaderValue contentDisposition;
var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);
if (hasContentDispositionHeader)
{
if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
{
await section.Body.CopyToAsync(targetStream);
}
else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
{
// Content-Disposition: form-data; name="key"
//
// value
// Do not limit the key name length here because the
// multipart headers length limit is already in effect.
var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
var encoding = GetEncoding(section);
using (var streamReader = new StreamReader(
section.Body,
encoding,
detectEncodingFromByteOrderMarks: true,
bufferSize: 1024,
leaveOpen: true))
{
// The value length limit is enforced by MultipartBodyLengthLimit
var value = await streamReader.ReadToEndAsync();
if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
{
value = String.Empty;
}
formAccumulator.Append(key.Value, value); // For .NET Core <2.0 remove ".Value" from key
if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit)
{
throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded.");
}
}
}
}
// Drains any remaining section body that has not been consumed and
// reads the headers for the next section.
section = await reader.ReadNextSectionAsync();
}
// Bind form data to a model
var formValueProvider = new FormValueProvider(
BindingSource.Form,
new FormCollection(formAccumulator.GetResults()),
CultureInfo.CurrentCulture);
return formValueProvider;
}
private static Encoding GetEncoding(MultipartSection section)
{
MediaTypeHeaderValue mediaType;
var hasMediaTypeHeader = MediaTypeHeaderValue.TryParse(section.ContentType, out mediaType);
// UTF-7 is insecure and should not be honored. UTF-8 will succeed in
// most cases.
if (!hasMediaTypeHeader || Encoding.UTF7.Equals(mediaType.Encoding) || mediaType.Encoding == null)
{
return Encoding.UTF8;
}
return mediaType.Encoding;
}
}
}
using System;
using System.IO;
using Microsoft.Net.Http.Headers;
namespace LookupServiceAPI.Helpers
{
public static class MultipartRequestHelper
{
public static bool IsMultipartContentType(string contentType)
{
return !string.IsNullOrEmpty(contentType)
&& contentType.IndexOf("multipart/", StringComparison.OrdinalIgnoreCase) >= 0;
}
public static bool HasFormDataContentDisposition(ContentDispositionHeaderValue contentDisposition)
{
// Content-Disposition: form-data; name="key";
return contentDisposition != null
&& contentDisposition.DispositionType.Equals("form-data")
&& string.IsNullOrEmpty(contentDisposition.FileName.Value)
&& string.IsNullOrEmpty(contentDisposition.FileNameStar.Value);
}
public static bool HasFileContentDisposition(ContentDispositionHeaderValue contentDisposition)
{
// Content-Disposition: form-data; name="myfile1"; filename="Misc 002.jpg"
return contentDisposition != null
&& contentDisposition.DispositionType.Equals("form-data")
&& (!string.IsNullOrEmpty(contentDisposition.FileName.ToString())
|| !string.IsNullOrEmpty(contentDisposition.FileNameStar.ToString()));
}
}
}
[Route("api/v0.1/data/excel")]
[ApiController]
public class DataExcelController : ControllerBase
{
[HttpPost, DisableRequestSizeLimit]
public async Task<IActionResult> ImportExcel()
{
var processID = Guid.NewGuid();
FormValueProvider multipartContent;
string tempFilePath = Path.GetTempPath() + processID;
using(var tempStream = System.IO.File.OpenWrite(tempFilePath))
{
multipartContent = await Request.StreamFile(tempStream);
}
/** Other unnecessary code **/
return Ok();
}
}
namespace LookupServiceAPI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
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;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
MemoryBufferThreshold
MultipartBodyLengthLimit
Content-Type
手动设置为 multipart/form-data
ValueLengthLimit
[DisableRequestSizeLimit]
1024 * 16
设置的
DefaultHeadersLengthLimit
(16384) 的大小限制,但我不知道为什么会这样。或者,如果序言应该比这更大,那么如何在不重新实现整个类集或等待 Microsoft 发布似乎不会进入管道的修复程序的情况下解决它:
最佳答案
我已经解决了我的问题。原来这是我使用的 URL。
为了解决我的问题,我意识到我正在发送到 http 端点而不是 https 端点,从而导致重定向。我将我的 url 从 http://localhost:5000/
更改为 https://localhost:5001/
,一切都立即开始工作。
有趣的是,这在 cURL 中也引起了一个问题,日志如下所示:
== Info: Connected to localhost (::1) port 5000 (#0)
=> Send header, 257 bytes (0x101)
0000: POST /api/v0.1/data/excel HTTP/1.1
0024: Host: localhost:5000
003a: User-Agent: curl/7.64.0
0053: Accept: */*
0060: cache-control: no-cache
0079: Content-Length: 13286446
0093: Content-Type: multipart/form-data; boundary=--------------------
00d3: ----7b12fc7773ed7878
00e9: Expect: 100-continue
00ff:
== Info: Expire in 1000 ms for 0 (transfer 0xa6aa80)
<= Recv header, 33 bytes (0x21)
0000: HTTP/1.1 307 Temporary Redirect
<= Recv header, 37 bytes (0x25)
0000: Date: Tue, 09 Apr 2019 18:04:24 GMT
<= Recv header, 17 bytes (0x11)
0000: Server: Kestrel
<= Recv header, 19 bytes (0x13)
0000: Content-Length: 0
<= Recv header, 54 bytes (0x36)
0000: Location: https://localhost:5001/api/v0.1/data/excel
== Info: HTTP error before end of send, stop sending
<= Recv header, 2 bytes (0x2)
0000:
== Info: Closing connection 0
multipart/form-data
上传会因该重定向而中断。如果有人有任何想法为什么,我很乐意学习。
关于c# - InvalidDataException : Multipart body length limit 16384 exceeded,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55582335/
当调用 func didBegin(_ contact: SKPhysicsContact) 的 SKScene 中发生接触时,需要确定哪个 SKPhysicsBody 是contact.bodyA
HTML: CSS: body { width : 1000px ; } header { width : 100% ; } 如果有这样的代码, 我认为页眉的宽度将与主体的
我刚刚通过网站完成设计,现在我正在尝试将整个 body 布置成一个整体,而不是不断重复的瓷砖。请问我该怎么做? 我不确定我说的是否有道理,但就像一张墙纸在拉伸(stretch),而不是 30 个小瓷砖
我试图在我的内部包装器上获得一个滚动条,而不是主体本身: CSS body { overflow: hidden; } #body_wrap { overflow-y: auto;
body { margin: 0px; border: 1px solid black; } #head { text-align: center; background: linea
关闭。这个问题是opinion-based .它目前不接受答案。 想要改进这个问题? 更新问题,以便 editing this post 可以用事实和引用来回答它. 关闭 9 年前。 Improv
我试图了解此 CSS 规则将应用于哪些元素: body h1, body .h1 { font-family: 'Open Sans', sans-serif !important;
此问题与使用 Jade templates 有关与 Express.js . 我知道当我写 layout.jade其中包含: !!! html body != body hea
我正在尝试为 body 设置不透明度。但是,我遇到了一个问题。 在body 上设置不透明度时,只有它的内容会受到影响。 背景不受不透明度的影响。 $("button").click(function(
我的游戏中有两个对象:球和星星 球是静态或动态的物体。 对于明星: 我需要知道星星何时与球相撞 但它需要穿过小球并且不受碰撞影响 我应该怎么做? 谢谢 袜套 最佳答案 您想使用 Sensors (6.
我以前问过这个问题,但所有答案都不起作用,所以我有一个示例页面,webpage .我有一个重新调整大小的菜单,我想在菜单外单击时关闭菜单,以及在第一次切换下拉菜单时让主体向下动画,这样下拉菜单就不会隐
我有一个漂浮在我其余内容上的井。我遇到的问题是,当它加载页面时,它会下推其余内容。我该如何更改它以便它悬停在所有内容上并且不会在页面加载时将内容下推。 这是页面加载的图像。 这是向下滚动页面的图片 请
在我的代码中我有这个: #body { background-color: #efeeef; clear: both; padding-bottom: 35px; } 还有这个
我想做以下事情。 $("a").click(function (event) { event.preventDefault(); $.get($(this).attr("href"),
在documentation在其他地方,我看到使用了 Body 但不知道它是什么。 谁能解释一下这三个选项是什么意思? from fastapi import Body from pydantic i
我试图在 body 加载后触发一个功能。我知道你可以从 body 标签中做到这一点,但如果可能的话,我更愿意从 JS 中做到这一点。 例如:document.getElementsByTagName(
在 Pymunk 中,当我旋转一个物体时,它的形状并没有旋转。当我施加一个冲动时,形状会如预期的那样同步移动。我的谷歌搜索表明 body 的形状应该在 body 旋转时旋转。我是否从根本上误解了旋转?
在我的移动网站/应用程序中使用 jQueryMobile 时,我刚刚开始遇到非常奇怪错误 编辑 我正在添加图片,可能更容易理解问题 edit2 我发现了这个问题。仍然好奇为什么会这样 如果您想查看原
我正在使用 Phaser.js 及其 p2 物理来模拟“流体”。你可以在this中看到创建一种流体体的示例(归功于 John Watson)。唯一可能的交互是鼠标移动。 我注意到一些有趣的特性可能有助
我认为是后一项, :not(body> element) 说明 body 标签中的所有“元素”元素。这是否与 同义 body >:not(element) ?? 最佳答案 body >:not(ele
我是一名优秀的程序员,十分优秀!