且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有自定义响应包装器的ASP.NET Core 3.1 Web API中的JSON响应中断

更新时间: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:

我们不必为上一章的HttpResponse.Body创建包装器,只要在将更改后的主体写入Response之前将ContentLength更改为null.尽管了解当控制器动作返回其值并写入响应主体时ASP.NET Core 2.2没有设置ContentLength的内容,但ASP.NET Core 3.1设置了ContentLength的内容却很有帮助.结果,当我们更改响应主体时,内容变得比设置的ContentLength更长.

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.