更新时间:2023-02-15 10:12:56
在使用自定义中间件更改响应正文的应用程序中,我们遇到了同样的问题.该页面很有帮助:
We were having this same problem in an application where we use custom middleware to change the response body. This page was helpful:
We didn't have to create a wrapper like in the above page for the HttpResponse.Body as long as we changed the ContentLength to null before writing our altered body to the Response. It was helpful though to learn what while ASP.NET Core 2.2 does not set ContentLength when the controller action returns its value and the response body is written, ASP.NET Core 3.1 does set the ContentLength. As a result, when we altered the response body, the content became longer than the set ContentLength.
我们有一些代码,可以在等待控制器动作之前用内存字符串替换响应主体.这样就可以捕获任何控制器方法的响应.然后更改响应,并将原始流还原到响应对象.然后将更改后的响应写入原始流中,并留在身体中.
We have code that replaces the response body with a memory string before the controller action is awaited. This is to be able to capture the response from any controller method. Then the response was altered and the original stream restored to the response object. Then the altered response was written to the body with its original stream in place.
发生的事情是,当中间件等待控制器响应时,响应设置了ContentLength.然后,当我们编写更改后的响应正文时,不会更新ContentLength.因此,接收到的json字符串被截断了.我们能够将ContentLength更改为更改后的内容的长度(或使用null,都起作用),如果,我们更改了在将更改的正文写入响应之前的长度.
What was happening was that when the middleware awaited the controller response, the response set the ContentLength. Then, when we wrote the altered response body, that ContentLength was not updated. So the received json string was truncated. We were able to change ContentLength to the length of the altered content (or use null, both worked), IF we change the length before writing the altered body to the response.