HttpStaticPagePlugin.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //------------------------------------------------------------------------------
  2. // 此代码版权(除特别声明或在XREF结尾的命名空间的代码)归作者本人若汝棋茗所有
  3. // 源代码使用协议遵循本仓库的开源协议及附加协议,若本仓库没有设置,则按MIT开源协议授权
  4. // CSDN博客:https://blog.csdn.net/qq_40374647
  5. // 哔哩哔哩视频:https://space.bilibili.com/94253567
  6. // Gitee源代码仓库:https://gitee.com/RRQM_Home
  7. // Github源代码仓库:https://github.com/RRQM
  8. // API首页:https://www.yuque.com/rrqm/touchsocket/index
  9. // 交流QQ群:234762506
  10. // 感谢您的下载和使用
  11. //------------------------------------------------------------------------------
  12. //------------------------------------------------------------------------------
  13. using System;
  14. using System.IO;
  15. using TouchSocket.Sockets;
  16. namespace TouchSocket.Http
  17. {
  18. /// <summary>
  19. /// Http静态内容插件
  20. /// </summary>
  21. public class HttpStaticPagePlugin : HttpPluginBase
  22. {
  23. private readonly FileCachePool fileCache;
  24. /// <summary>
  25. /// 构造函数
  26. /// </summary>
  27. public HttpStaticPagePlugin()
  28. {
  29. fileCache = new FileCachePool();
  30. }
  31. /// <summary>
  32. /// 静态文件缓存。
  33. /// </summary>
  34. public FileCachePool FileCache => fileCache;
  35. /// <summary>
  36. /// 添加静态
  37. /// </summary>
  38. /// <param name="path">Static content path</param>
  39. /// <param name="prefix">Cache prefix (default is "/")</param>
  40. /// <param name="filter">Cache filter (default is "*.*")</param>
  41. /// <param name="timeout">Refresh cache timeout (default is 1 hour)</param>
  42. public void AddFolder(string path, string prefix = "/", string filter = "*.*", TimeSpan? timeout = null)
  43. {
  44. timeout ??= TimeSpan.FromHours(1);
  45. fileCache.InsertPath(path, prefix, filter, timeout.Value, null);
  46. }
  47. /// <summary>
  48. /// Clear static content cache
  49. /// </summary>
  50. public void ClearFolder()
  51. {
  52. fileCache.Clear();
  53. }
  54. /// <summary>
  55. /// Remove static content cache
  56. /// </summary>
  57. /// <param name="path">Static content path</param>
  58. public void RemoveFolder(string path)
  59. {
  60. fileCache.RemovePath(path);
  61. }
  62. /// <summary>
  63. /// <inheritdoc/>
  64. /// </summary>
  65. /// <param name="client"></param>
  66. /// <param name="e"></param>
  67. protected override void OnGet(ITcpClientBase client, HttpContextEventArgs e)
  68. {
  69. if (fileCache.Find(e.Context.Request.RelativeURL, out byte[] data))
  70. {
  71. e.Context.Response
  72. .SetStatus()
  73. .SetContentTypeByExtension(Path.GetExtension(e.Context.Request.RelativeURL))
  74. .SetContentLength(data.Length)
  75. .WriteContent(data);
  76. e.Handled = true;
  77. }
  78. base.OnGet(client, e);
  79. }
  80. }
  81. }