IApplicationBuilderExtensions_UseStaticFiles.cs 3.3 KB

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