Устранение проблемы с настраиваемым ответом. .NET Core API Gateway Ocelot - ПО промежуточного слоя

Добрый день, у меня проблема с настраиваемым ответом в API Gateway Ocelot с промежуточным ПО. внутри FormatResponse (context.Response) я изменяю ответ для конкретной конечной точки и вижу новый ответ при отладке, но получаю исходный ответ в окончательном результате на почтальоне. пример: исходный ответ

{
"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}";
        }

Ссылка: https://www.abhith.net/blog/dotnet-core-api-gateway-ocelot-logging-http-requests-response-including-headers-body/


person M.Alhadad    schedule 14.02.2021    source источник


Ответы (1)


Лучший ответ Ричарда Диминга: https://www.codeproject.com/Questions/5294847/Fix-issue-with-custom-response-NET-core-API-gatewa

person M.Alhadad    schedule 16.02.2021