如何解决修复自定义响应问题“.NET Core API Gateway Ocelot - Middleware”
美好的一天, 我在带有中间件的 API Gateway Ocelot 中遇到自定义响应问题。 在 FormatResponse(context.Response) 中,我更改了特定端点的响应,并在调试时看到了新响应,但我在 postman 的最终结果中收到了原始响应。 前任 : 原始回复
{
"name":"mo"
}
更改后会
{
"name":"mo123"
}
我的代码
// .NET Core 3.1
public async Task InvokeAsync(HttpContext context)
{
context.Request.EnableBuffering();
var builder = new StringBuilder();
var request = await FormatRequest(context.Request);
builder.Append("Request: ").AppendLine(request);
builder.AppendLine("Request headers:");
foreach (var header in context.Request.Headers)
{
builder.Append(header.Key).Append(':').AppendLine(header.Value);
}
//Copy a pointer to the original response body stream
var originalBodyStream = context.Response.Body;
//Create a new memory stream...
using var responseBody = new MemoryStream();
//...and use that for the temporary response body
context.Response.Body = responseBody;
//Continue down the Middleware pipeline,eventually returning to this class
await _next(context);
//Format the response from the server
var response = await FormatResponse(context.Response); // here,i see new respose
builder.Append("Response: ").AppendLine(response);
builder.AppendLine("Response headers: ");
foreach (var header in context.Response.Headers)
{
builder.Append(header.Key).Append(':').AppendLine(header.Value);
}
//Save log to chosen datastore
_logger.LogInformation(builder.ToString());
//Copy the contents of the new memory stream (which contains the response) to the original
// stream,which is then returned to the client.
await responseBody.CopyToAsync(originalBodyStream);
}
private async Task<string> FormatResponse(HttpResponse response)
{
//We need to read the response stream from the beginning...
response.Body.Seek(0,SeekOrigin.Begin);
//...and copy it into a string
string text = await new StreamReader(response.Body).ReadToEndAsync();
text = CustomRes(text); //************************ here,I change response
//We need to reset the reader for the response so that the client can read it.
response.Body.Seek(0,SeekOrigin.Begin);
//Return the string for the response,including the status code (e.g. 200,404,401,etc.)
return $"{response.StatusCode}: {text}";
}
解决方法
Richard Deeming 的最佳答案: https://www.codeproject.com/Questions/5294847/Fix-issue-with-custom-response-NET-core-API-gatewa
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。