我想在我的自定义 InvalidModelStateResponseFactory
处理程序中获取 HTTP 请求正文,它总是返回空。
我在 SO 和其他网站上尝试了很多解决方案,但似乎使用 EnableRewind
在 InvalidModelStateResponseFactory
中没有效果。
那么是否有任何特殊情况我可以在 InvalidModelStateResponseFactory
中获取请求主体?
我在 Startup.cs 中的代码
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.Configure<ApiBehaviorOptions>(options =>
{
options.InvalidModelStateResponseFactory = actionContext =>
{
actionContext.HttpContext.Request.EnableRewind();
using(StreamReader stream = new StreamReader(actionContext.HttpContext.Request.Body))
{
string body = stream.ReadToEnd(); //body is always empty
}
return new BadRequestObjectResult(/*Some Error Model*/);
};
});
}
最佳答案
我可以通过简单的更改使您提供的示例生效,方法是:
actionContext.HttpContext.Request.EnableRewind();
与:
actionContext.HttpContext.Request.Body.Position = 0;
一旦主体被读取(由 MVC 本身),流的位置需要在尝试再次读取之前重置为开头。
在我的测试中,我发现我根本不需要调用 EnableRewind
,但如果您需要这样做,我希望它是在您的示例中称为太晚了。如果像我展示的那样将 Position
设置为 0
不能单独工作,您可能需要添加一个自定义中间件来设置倒带:
app.Use(async (ctx, next) =>
{
ctx.Request.EnableRewind();
await next();
});
这需要在 UseMvc
之前添加,但正如我所说,我在测试中发现不需要它,但我预计情况并非总是如此。
关于c# - 在自定义 InvalidModelStateResponseFactory asp.net core 2.2 中读取请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55430076/