diff --git a/src/Lykke.Common.ApiLibrary/Middleware/BufferingHelper.cs b/src/Lykke.Common.ApiLibrary/Middleware/BufferingHelper.cs new file mode 100644 index 0000000..4ca9718 --- /dev/null +++ b/src/Lykke.Common.ApiLibrary/Middleware/BufferingHelper.cs @@ -0,0 +1,50 @@ +using System; +using System.IO; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.WebUtilities; + +namespace Lykke.Common.ApiLibrary.Middleware +{ + internal static class BufferingHelper + { + private const int DefaultBufferThreshold = 1024 * 30; + + private static string _tempDirectory; + + public static HttpRequest EnableRewind(this HttpRequest request) + { + if (request == null) + throw new ArgumentNullException(nameof(request)); + + var body = request.Body; + if (!body.CanSeek) + { + var fileStream = new FileBufferingReadStream(body, DefaultBufferThreshold, null, GetTempDirectory); + request.Body = fileStream; + request.HttpContext.Response.RegisterForDispose(fileStream); + } + + return request; + } + + private static string GetTempDirectory() + { + if (_tempDirectory != null) + return _tempDirectory; + + // Look for folders in the following order. + var temp = Environment.GetEnvironmentVariable("ASPNETCORE_TEMP") // ASPNETCORE_TEMP - User set temporary location. + ?? Path.GetTempPath(); // Fall back. + + if (!Directory.Exists(temp)) + { + // TODO: ??? + throw new DirectoryNotFoundException(temp); + } + + _tempDirectory = temp; + + return _tempDirectory; + } + } +} diff --git a/src/Lykke.Common.ApiLibrary/Middleware/MiddlewareApplicationBuilderExtensions.cs b/src/Lykke.Common.ApiLibrary/Middleware/MiddlewareApplicationBuilderExtensions.cs index f65bbdb..dea6d05 100644 --- a/src/Lykke.Common.ApiLibrary/Middleware/MiddlewareApplicationBuilderExtensions.cs +++ b/src/Lykke.Common.ApiLibrary/Middleware/MiddlewareApplicationBuilderExtensions.cs @@ -3,7 +3,6 @@ using JetBrains.Annotations; using Lykke.Common.Log; using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http.Internal; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.DependencyInjection; @@ -88,7 +87,7 @@ public static void UseLykkeMiddleware( app.UseMiddleware(logFactory); } } - + /// /// Configure application to use forwarded headers /// @@ -99,10 +98,10 @@ public static void UseLykkeForwardedHeaders(this IApplicationBuilder app) { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost }; - + forwardingOptions.KnownNetworks.Clear(); //its loopback by default forwardingOptions.KnownProxies.Clear(); - + app.UseForwardedHeaders(forwardingOptions); } }