我相信您遇到的问题是您的cccc
空空回来。这可能是因为当您进入控制器时,请求正文流已被读取。这是有道理的——必须有一些东西来填充value
参数给你。因此,在这个阶段尝试倒回流已经为时已晚。
ASP.NET 博客 https://devblogs.microsoft.com/aspnet/re-reading-asp-net-core-request-bodies-with-enablebuffering/有一篇文章介绍了如何解决此问题:您需要一个自定义中间件,并且需要将其插入 MVC 中间件上方的管道中。
启动.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<CustomMiddleware>(); // register your custom middleware with DI container
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMiddleware<CustomMiddleware>(); // inject your middleware before MVC injects theirs
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
那么您的自定义中间件可能如下所示:
自定义中间件.cs
public class CustomMiddleware : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
context.Request.EnableBuffering(); // now you can do it
// Leave the body open so the next middleware can read it.
using (var reader = new StreamReader(context.Request.Body, encoding: Encoding.UTF8, detectEncodingFromByteOrderMarks: false, leaveOpen: true))
{
var body = await reader.ReadToEndAsync();
context.Items.Add("body", body); // there are ways to pass data from middleware to controllers downstream. this is one. see https://stackoverflow.com/questions/46601757/c-sharp-dotnet-core-2-pass-data-from-middleware-filter-to-controller-method for more
// Reset the request body stream position so the next middleware can read it
context.Request.Body.Position = 0;
}
// Call the next delegate/middleware in the pipeline
await next(context);
}
}
最后在你的控制器中,你将从中获取主体context
像这样:
// PUT: api/Test/5
[HttpPut("{id}")]
public async Task<string> PutAsync(int id, [FromBody]ProductInfo value)
{
var ccccc = (string)HttpContext.Items["body"];
return ccccc;
}
此方法有一些注意事项,本文对此进行了讨论。注意巨大的请求主体并相应地调整缓冲区大小。