IApplicationBuilderExtensions_UseStaticFiles.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.Extensions.FileProviders;
  3. using Vit.Core.Util.Common;
  4. using Vit.WebHost;
  5. namespace Vit.Extensions
  6. {
  7. public static class IApplicationBuilderExtensions_UseStaticFiles
  8. {
  9. public static IApplicationBuilder UseStaticFiles(this IApplicationBuilder data, StaticFilesConfig config)
  10. {
  11. if (config == null || data == null) return data;
  12. #region (x.1)UseStaticFiles
  13. var staticfileOptions = new StaticFileOptions();
  14. //(x.x.1)requestPath
  15. if (!string.IsNullOrEmpty(config.requestPath))
  16. {
  17. staticfileOptions.RequestPath = new Microsoft.AspNetCore.Http.PathString(config.requestPath);
  18. }
  19. //(x.x.2)FileProvider
  20. IFileProvider fileProvider;
  21. if (!string.IsNullOrWhiteSpace(config.rootPath))
  22. {
  23. fileProvider = new PhysicalFileProvider(config.rootPath);
  24. }
  25. else
  26. {
  27. fileProvider = new PhysicalFileProvider(CommonHelp.GetAbsPath("wwwroot"));
  28. }
  29. staticfileOptions.FileProvider = fileProvider;
  30. //(x.x.3)OnInitStaticFileOptions
  31. config.OnInitStaticFileOptions?.Invoke(staticfileOptions);
  32. #region (x.x.4)Response Headers
  33. if (config.responseHeaders != null)
  34. {
  35. staticfileOptions.OnPrepareResponse +=
  36. ctx =>
  37. {
  38. var Headers = ctx.Context.Response.Headers;
  39. foreach (var kv in config.responseHeaders)
  40. {
  41. Headers[kv.Key] = kv.Value;
  42. }
  43. };
  44. }
  45. #endregion
  46. //(x.x.5)contentTypeProvider
  47. if (config.contentTypeProvider != null)
  48. {
  49. staticfileOptions.ContentTypeProvider = config.contentTypeProvider;
  50. }
  51. //(x.x.6)UseDefaultFiles
  52. if (config.defaultFileNames != null)
  53. {
  54. data.UseDefaultFiles(new DefaultFilesOptions
  55. {
  56. DefaultFileNames = config.defaultFileNames,
  57. FileProvider= fileProvider
  58. });
  59. }
  60. //(x.x.7)UseStaticFiles
  61. data.UseStaticFiles(staticfileOptions);
  62. #endregion
  63. //(x.2)UseDirectoryBrowser
  64. if (config.useDirectoryBrowser == true)
  65. {
  66. var options = new DirectoryBrowserOptions {
  67. RequestPath = staticfileOptions.RequestPath,
  68. FileProvider = fileProvider
  69. };
  70. data.UseDirectoryBrowser(options);
  71. }
  72. return data;
  73. }
  74. }
  75. }