我想您遇到的问题是您的
cccc
返回为空。这很可能是因为在进入控制器时,请求正文流已经被读取完了。这是有道理的 - 必须有一些东西来填充
value
参数。所以现在尝试倒带流已经太迟了。
ASP.NET Blog有一篇文章介绍了如何解决这个问题:您需要一个自定义中间件,并将其插入到MVC中间件之上的管道中。
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<CustomMiddleware>();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMiddleware<CustomMiddleware>();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
然后您的自定义中间件可能如下所示:
CustomMiddleware.cs
public class CustomMiddleware : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
context.Request.EnableBuffering();
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);
context.Request.Body.Position = 0;
}
await next(context);
}
}
最后,在您的控制器中,您将像这样从context
获取主体:
[HttpPut("{id}")]
public async Task<string> PutAsync(int id, [FromBody]ProductInfo value)
{
var ccccc = (string)HttpContext.Items["body"];
return ccccc;
}
这种方法有一些注意事项,在文章中进行了讨论。要注意大请求体并相应地调整缓冲区大小。