BodyRewindMiddleware.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System.Text;
  2. namespace EVCB_OCPP.DBAPI.Middleware;
  3. public sealed class BodyRewindMiddleware
  4. {
  5. private readonly RequestDelegate _next;
  6. public BodyRewindMiddleware(RequestDelegate next)
  7. {
  8. _next = next;
  9. }
  10. public async Task Invoke(HttpContext context)
  11. {
  12. string body = await new StreamReader(context.Request.Body).ReadToEndAsync();
  13. context.Items.Add("PreloadBody", body);
  14. context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body));
  15. await _next(context);
  16. //using (var injectedRequestStream = new MemoryStream())
  17. //{
  18. // var bytesToWrite = System.Text.Encoding.UTF8.GetBytes(body);
  19. // injectedRequestStream.Write(bytesToWrite, 0, bytesToWrite.Length);
  20. // injectedRequestStream.Seek(0, SeekOrigin.Begin);
  21. // context.Request.Body = injectedRequestStream;
  22. // await _next(context);
  23. //}
  24. }
  25. }
  26. public static class BodyRewindExtensions
  27. {
  28. public static IApplicationBuilder EnableRequestBodyRewind(this IApplicationBuilder app)
  29. {
  30. if (app == null)
  31. {
  32. throw new ArgumentNullException(nameof(app));
  33. }
  34. return app.UseMiddleware<BodyRewindMiddleware>();
  35. }
  36. public static string GetPreLoadBody(this HttpContext httpContext)
  37. {
  38. return httpContext.Items["PreloadBody"] as string;
  39. }
  40. }