SwaggerUiMiddleware.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using Microsoft.AspNetCore.Http;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. namespace VCommon.VSwaggerUI.VAspNetCore
  5. {
  6. internal class SwaggerUiMiddleware
  7. {
  8. internal static ISwaggerUiResourceProvider ResourceProvider;
  9. internal static string BasePath;
  10. private readonly RequestDelegate _next;
  11. public SwaggerUiMiddleware(RequestDelegate next) => _next = next;
  12. public async Task Invoke(HttpContext context)
  13. {
  14. var requestPath = context.Request.Path.Value?.ToLower();
  15. if (requestPath?.StartsWith(BasePath) != true)
  16. {
  17. await _next.Invoke(context);
  18. return;
  19. }
  20. var path = requestPath.Substring(BasePath.Length);
  21. if (path == "/")
  22. {
  23. var qs = context.Request.QueryString.ToString();
  24. var html = ResourceProvider.GetIndex(qs.Length == 0 ? "api/" : qs.Substring(1));
  25. context.Response.ContentType = "text/html";
  26. await context.Response.WriteAsync(html);
  27. }
  28. else
  29. {
  30. var fileName = Path.GetFileName(path);
  31. var bin = ResourceProvider.GetBinResource(fileName);
  32. if (null == bin)
  33. {
  34. context.Response.StatusCode = 404;
  35. }
  36. else
  37. {
  38. if (Path.GetExtension(fileName).ToLower() == ".css")
  39. context.Response.ContentType = "text/css";
  40. await context.Response.Body.WriteAsync(bin);
  41. }
  42. }
  43. }
  44. }
  45. }