【发布时间】:2022-01-24 18:36:48
【问题描述】:
客户端出现异常,提示复制流内容时出错,然后响应提前结束。
我想不出解决方案。在服务器端,我有修改响应流的 asp.net core web api。它实际上读取控制器发送的内容并将其加密为字符串,然后写入响应流。
此外,当内容类型为 text/plain 时,响应会显示在 Postman 上,但当内容类型为 application/json 时,内容不会显示,但在标题中我可以看到内容长度有一些数字。而对于客户端,两种内容类型都会出现上述异常。
那么我的中间件代码中缺少什么?我知道这是导致问题的原因,因为当我在 startup.cs 中注释掉 MyMiddleware 时,正常流程可以正常工作。
下面是服务器端中间件中的Invoke function
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
string reponseContent = string.Empty;
// Store the "pre-modified" response stream.
var existingBody = context.Response.Body;
using (var newBody = new MemoryStream())
{
// We set the response body to our stream so we can read after the chain of middlewares have been called.
context.Response.Body = newBody;
await next(context);
// Set the stream back to the original.
context.Response.Body = existingBody;
newBody.Seek(0, SeekOrigin.Begin);
//reading the content
var contentReader = new StreamReader(newBody);
reponseContent = await contentReader.ReadToEndAsync();
string encryptedData = _cryptoService.Encrypt(reponseContent);
// Send our modified content to the response body.
await context.Response.WriteAsync(encryptedData);
}
【问题讨论】:
-
你能不能尝试用这个
reponseContent = await contentReader.ReadAsStringAsync();替换这个`reponseContent = await contentReader.ReadToEndAsync();`行,如果有任何变化或错误消息发生变化,请告诉我。 -
另外分享您的
_cryptoService服务详情,以便我们重现问题。 -
@MdFaridUddinKiron
contentReader没有ReadAsStringAsync()方法。同样_cryptoService.Encrypt()将字符串作为输入并使用客户端的公钥加密数据并返回base64string。我认为问题在于写入响应流,也许我在写入响应流时遗漏了一些东西。 -
您好,请您检查一下答案并仔细检查您的中间件是如何在您的
startus.cs类上调用它的。我认为你可能有实施glitch
标签: c# asp.net-core postman