#事故现场
在asp.net core web api 项目中,框架为.NET5,启动倒带方式,为 request.EnableBuffering()
但是在过滤器中使用此方法时出现异常,request.body的长度总是为0,说明在请求到达过滤器时Steam已经被读取了。
public class TestFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
var request = context.HttpContext.Request;
//启动倒带方式
request.EnableBuffering();
if (request.Method.ToLower().Equals("post"))
{
request.Body.Position = 0;
using var requestReader = new StreamReader(request.Body);
var requestContent = requestReader.ReadToEnd();
request.Body.Position = 0;
}
}
public override void OnActionExecuted(ActionExecutedContext context)
{
base.OnActionExecuted(context);
}
}
#解决方法
1、在项目的Startup
类中的Configure
方法中添加如下配置:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//其他代码
//启动倒带方式
app.Use(next => context =>
{
context.Request.EnableBuffering();
return next(context);
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
注意:
EnableBuffering
的配置一定要在UseEndpoints
的前面;
2、修改过后滤器中的代码:
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
var request = context.HttpContext.Request;
if (request.Method.ToLower().Equals("post"))
{
request.Body.Position = 0;
using var requestReader = new StreamReader(request.Body);
var requestContent = requestReader.ReadToEnd();
request.Body.Position = 0;
}
}