在我的ASP.NET 6应用程序中,我有这样一个端点,其中我想直接读取请求体流:
[HttpPost("{id}/Binary")]
[OpenApiBodyParameter("application/octet-stream")]
public async Task UploadBinary([FromRoute] Guid id, [FromHeader(Name = "Content-Length")] long contentLength)
{
// Trying to read Request.Body stream here fails with
// "Unexpected end of request content" exception.
// My real code looks different, but trying to read just
// one byte can reproduce the problem:
var buffer = new byte[1];
await Request.Body.ReadAsync(buffer, 0, 1);
}读取请求体会产生“请求内容的意外结束”异常。
[08:51:27 ERR] An unhandled exception has occurred while executing the request.
Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Unexpected end of request content.
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1ContentLengthMessageBody.ReadAsyncInternal(CancellationToken cancellationToken)
at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder`1.StateMachineBox`1.System.Threading.Tasks.Sources.IValueTaskSource<TResult>.GetResult(Int16 token)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.ReadAsyncInternal(Memory`1 destination, CancellationToken cancellationToken)
at ... (my own action)我很确定这是因为有些中间件读取请求体,这样我就无法(再次)在代码中读取它。
我如何才能知道是哪个中间件导致了不必要的读取?(避免这样做?)
我是这样设置请求管道的:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseSerilogRequestLogging();
app.UseStaticFiles();
if (!env.IsDevelopment())
app.UseSpaStaticFiles();
app.UseOpenApi();
app.UseSwaggerUi3(c => {
c.OAuth2Client = new NSwag.AspNetCore.OAuth2ClientSettings() { ClientId = null, ClientSecret = null };
});
app.UseCors(builder => builder.WithOrigins("localhost", "http://localhost:4200", "http://localhost:4210")
.AllowAnyHeader().AllowAnyMethod().AllowCredentials());
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApps/manage-app";
if (env.IsDevelopment() && !env.IsEnvironment("RunLocal"))
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}我怀疑UseSerilogRequestLogging可能会导致对请求体的不必要的阅读,但是注释掉它并不能解决我的问题。
还有什么能引起我的问题?
发布于 2022-08-03 11:04:49
解决了!
根本原因实际上是在客户端(HttpClient过早地被释放)。
https://stackoverflow.com/questions/73208732
复制相似问题