IApplicationBuilderExtensions_UseStaticFiles.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.Extensions.FileProviders;
  3. using System.Collections.Generic;
  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. //(x.1)
  13. var staticfileOptions = new StaticFileOptions();
  14. #region (x.2)FileProvider
  15. if (!string.IsNullOrWhiteSpace(config.rootPath))
  16. {
  17. staticfileOptions.FileProvider = new PhysicalFileProvider(config.rootPath);
  18. }
  19. #endregion
  20. //(x.3)OnInitStaticFileOptions
  21. config.OnInitStaticFileOptions?.Invoke(staticfileOptions);
  22. #region (x.4)Response Headers
  23. if (config.responseHeaders != null)
  24. {
  25. staticfileOptions.OnPrepareResponse +=
  26. ctx =>
  27. {
  28. var Headers = ctx.Context.Response.Headers;
  29. foreach (var kv in config.responseHeaders)
  30. {
  31. Headers[kv.Key] = kv.Value;
  32. }
  33. };
  34. }
  35. #endregion
  36. //(x.5)contentTypeProvider
  37. if (config.contentTypeProvider != null)
  38. {
  39. staticfileOptions.ContentTypeProvider = config.contentTypeProvider;
  40. }
  41. #region (x.6)UseDefaultFiles
  42. if (config.defaultFileNames != null)
  43. {
  44. data.UseDefaultFiles(new DefaultFilesOptions
  45. {
  46. DefaultFileNames = config.defaultFileNames
  47. });
  48. }
  49. #endregion
  50. //(x.7)UseStaticFiles
  51. data.UseStaticFiles(staticfileOptions);
  52. //(x.8)UseDirectoryBrowser
  53. if (config.useDirectoryBrowser == true)
  54. {
  55. data.UseDirectoryBrowser(new DirectoryBrowserOptions { FileProvider = staticfileOptions.FileProvider });
  56. }
  57. return data;
  58. }
  59. }
  60. }