IApplicationBuilderExtensions_UseStaticFiles.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.Extensions.FileProviders;
  3. using Vit.WebHost;
  4. namespace Vit.Extensions
  5. {
  6. public static class IApplicationBuilderExtensions_UseStaticFiles
  7. {
  8. public static IApplicationBuilder UseStaticFiles(this IApplicationBuilder data, StaticFilesConfig config)
  9. {
  10. if (config == null || data==null) return data;
  11. //(x.1)
  12. var staticfileOptions = new StaticFileOptions();
  13. #region (x.2)FileProvider
  14. if (!string.IsNullOrWhiteSpace(config.rootPath))
  15. {
  16. staticfileOptions.FileProvider = new PhysicalFileProvider(config.rootPath);
  17. }
  18. #endregion
  19. //(x.3)OnInitStaticFileOptions
  20. config.OnInitStaticFileOptions?.Invoke(staticfileOptions);
  21. #region (x.4)Response Headers
  22. if (config.responseHeaders != null)
  23. {
  24. staticfileOptions.OnPrepareResponse +=
  25. ctx =>
  26. {
  27. var Headers = ctx.Context.Response.Headers;
  28. foreach (var kv in config.responseHeaders)
  29. {
  30. Headers[kv.Key] = kv.Value;
  31. }
  32. };
  33. }
  34. #endregion
  35. //(x.5)contentTypeProvider
  36. if (config.contentTypeProvider != null)
  37. {
  38. staticfileOptions.ContentTypeProvider = config.contentTypeProvider;
  39. }
  40. data.UseStaticFiles(staticfileOptions);
  41. return data;
  42. }
  43. }
  44. }