MiddlewareExtension.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. using AutoMapper;
  2. using AutoMapper.Extensions.ExpressionMapping;
  3. using CacheManager.Core;
  4. using Masuit.MyBlogs.Core.Configs;
  5. using Masuit.Tools.AspNetCore.Mime;
  6. using Microsoft.AspNetCore.Mvc;
  7. using Microsoft.AspNetCore.Mvc.Filters;
  8. using Microsoft.AspNetCore.ResponseCompression;
  9. using Microsoft.Extensions.WebEncoders;
  10. using Microsoft.Net.Http.Headers;
  11. using Newtonsoft.Json;
  12. using Newtonsoft.Json.Serialization;
  13. using System.IO.Compression;
  14. using System.Reflection;
  15. using System.Text.Encodings.Web;
  16. using System.Text.Unicode;
  17. using ConfigurationBuilder = CacheManager.Core.ConfigurationBuilder;
  18. namespace Masuit.MyBlogs.Core.Extensions
  19. {
  20. public static class MiddlewareExtension
  21. {
  22. /// <summary>
  23. /// 缓存配置
  24. /// </summary>
  25. /// <param name="services"></param>
  26. /// <returns></returns>
  27. public static IServiceCollection AddCacheConfig(this IServiceCollection services)
  28. {
  29. var jss = new JsonSerializerSettings
  30. {
  31. NullValueHandling = NullValueHandling.Ignore,
  32. ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
  33. TypeNameHandling = TypeNameHandling.Auto
  34. };
  35. services.AddSingleton(typeof(ICacheManager<>), typeof(BaseCacheManager<>));
  36. services.AddSingleton(new ConfigurationBuilder().WithRedisConfiguration("redis", AppConfig.Redis).WithJsonSerializer(jss, jss).WithMaxRetries(5).WithRetryTimeout(100).WithRedisCacheHandle("redis").WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMinutes(5))
  37. .Build());
  38. return services;
  39. }
  40. /// <summary>
  41. /// automapper
  42. /// </summary>
  43. /// <param name="services"></param>
  44. /// <returns></returns>
  45. public static IServiceCollection AddMapper(this IServiceCollection services)
  46. {
  47. var mc = new MapperConfiguration(cfg => cfg.AddExpressionMapping().AddProfile(new MappingProfile()));
  48. services.AddAutoMapper(cfg => cfg.AddExpressionMapping().AddProfile(new MappingProfile()), Assembly.GetExecutingAssembly());
  49. services.AddSingleton(mc);
  50. return services;
  51. }
  52. /// <summary>
  53. /// mvc
  54. /// </summary>
  55. /// <param name="services"></param>
  56. /// <returns></returns>
  57. public static IServiceCollection AddMyMvc(this IServiceCollection services)
  58. {
  59. services.AddMvc(options =>
  60. {
  61. options.ReturnHttpNotAcceptable = true;
  62. options.Filters.Add<ExceptionFilter>();
  63. }).AddNewtonsoftJson(options =>
  64. {
  65. options.SerializerSettings.ContractResolver = new DefaultContractResolver();
  66. options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
  67. }).AddControllersAsServices().AddViewComponentsAsServices().AddTagHelpersAsServices(); // MVC
  68. services.Configure<WebEncoderOptions>(options =>
  69. {
  70. options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);
  71. }); //解决razor视图中中文被编码的问题
  72. return services;
  73. }
  74. /// <summary>
  75. /// 输出缓存
  76. /// </summary>
  77. /// <param name="services"></param>
  78. /// <returns></returns>
  79. public static IServiceCollection AddResponseCache(this IServiceCollection services)
  80. {
  81. services.AddResponseCaching(); //注入响应缓存
  82. services.Configure<BrotliCompressionProviderOptions>(options =>
  83. {
  84. options.Level = CompressionLevel.Fastest;
  85. }).Configure<GzipCompressionProviderOptions>(options =>
  86. {
  87. options.Level = CompressionLevel.Optimal;
  88. }).AddResponseCompression(options =>
  89. {
  90. options.EnableForHttps = true;
  91. options.Providers.Add<BrotliCompressionProvider>();
  92. options.Providers.Add<GzipCompressionProvider>();
  93. options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[]
  94. {
  95. "text/html; charset=utf-8",
  96. "application/xhtml+xml",
  97. "application/atom+xml",
  98. "image/svg+xml"
  99. });
  100. });
  101. return services;
  102. }
  103. /// <summary>
  104. /// 添加静态资源打包
  105. /// </summary>
  106. /// <param name="app"></param>
  107. /// <returns></returns>
  108. public static IApplicationBuilder UseBundles(this IApplicationBuilder app)
  109. {
  110. app.UseBundling(bundles =>
  111. {
  112. bundles.AddCss("/main.css")
  113. .Include("/fonts/icomoon.css")
  114. .Include("/Content/jquery.paging.css")
  115. .Include("/Content/common/reset.css")
  116. .Include("/Content/common/loading.css")
  117. .Include("/Content/common/style.css")
  118. .Include("/Content/common/articlestyle.css")
  119. .Include("/Content/common/leaderboard.css")
  120. .Include("/Assets/breadcrumb/style.css")
  121. .Include("/Assets/nav/css/style.css");
  122. bundles.AddCss("/filemanager.css")
  123. .Include("/Content/bootswatch.min.css")
  124. .Include("/fonts/icomoon.css")
  125. .Include("/ng-views/filemanager/css/animations.css")
  126. .Include("/ng-views/filemanager/css/dialogs.css")
  127. .Include("/ng-views/filemanager/css/main.css")
  128. .Include("/Content/common/loading.min.css");
  129. bundles.AddCss("/dashboard.css")
  130. .Include("/fonts/icomoon.css")
  131. .Include("/Assets/jedate/jedate.css")
  132. .Include("/Assets/fileupload/filestyle.css")
  133. .Include("/Content/common/loading.min.css")
  134. .Include("/Content/checkbox.min.css")
  135. .Include("/ng-views/css/app.css");
  136. bundles.AddCss("/article.css")
  137. .Include("/Assets/jquery.tocify/jquery.tocify.css")
  138. .Include("/Assets/UEditor/third-party/SyntaxHighlighter/styles/shCore.css")
  139. .Include("/Assets/highlight/css/highlight.css");
  140. bundles.AddJs("/main.js")
  141. .Include("/Scripts/jquery.query.js")
  142. .Include("/Scripts/jquery.paging.js")
  143. .Include("/Scripts/ripplet.js")
  144. .Include("/Scripts/global/scripts.js")
  145. .Include("/Scripts/platform.js")
  146. .Include("/Assets/newsbox/jquery.bootstrap.newsbox.js")
  147. .Include("/Assets/tagcloud/js/tagcloud.js")
  148. .Include("/Assets/scrolltop/js/scrolltop.js")
  149. .Include("/Assets/nav/js/main.js");
  150. bundles.AddJs("/filemanager.js")
  151. .Include("/Scripts/ng-file-upload.min.js")
  152. .Include("/ng-views/filemanager/js/app.js")
  153. .Include("/ng-views/filemanager/js/directives/directives.js")
  154. .Include("/ng-views/filemanager/js/filters/filters.js")
  155. .Include("/ng-views/filemanager/js/providers/config.js")
  156. .Include("/ng-views/filemanager/js/entities/chmod.js")
  157. .Include("/ng-views/filemanager/js/entities/item.js")
  158. .Include("/ng-views/filemanager/js/services/apihandler.js")
  159. .Include("/ng-views/filemanager/js/services/apimiddleware.js")
  160. .Include("/ng-views/filemanager/js/services/filenavigator.js")
  161. .Include("/ng-views/filemanager/js/providers/translations.js")
  162. .Include("/ng-views/filemanager/js/controllers/main.js")
  163. .Include("/ng-views/filemanager/js/controllers/selector-controller.js");
  164. bundles.AddJs("/article.js")
  165. .Include("/Assets/highlight/js/highlight.js")
  166. .Include("/Assets/UEditor/third-party/SyntaxHighlighter/scripts/shCore.js")
  167. .Include("/Assets/UEditor/third-party/SyntaxHighlighter/scripts/bundle.min.js")
  168. .Include("/Assets/jquery.tocify/jquery.tocify.js")
  169. .Include("/Scripts/global/article.js")
  170. .Include("/Assets/highlight/js/highlight.js");
  171. });
  172. return app;
  173. }
  174. }
  175. public class ExceptionFilter : IExceptionFilter, IFilterMetadata
  176. {
  177. public void OnException(ExceptionContext context)
  178. {
  179. if (context.Exception is NotFoundException)
  180. {
  181. context.HttpContext.Response.StatusCode = 404;
  182. string accept = context.HttpContext.Request.Headers[HeaderNames.Accept] + "";
  183. context.Result = true switch
  184. {
  185. _ when accept.StartsWith("image") => new VirtualFileResult("/Assets/images/404/4044.jpg", ContentType.Jpeg),
  186. _ when accept.StartsWith("application/json") || context.HttpContext.Request.Method == HttpMethods.Post => new JsonResult(new
  187. {
  188. StatusCode = 404,
  189. Success = false,
  190. Message = "页面未找到!"
  191. }),
  192. _ => new ViewResult()
  193. {
  194. ViewName = "/Views/Error/Index.cshtml"
  195. }
  196. };
  197. context.ExceptionHandled = true;
  198. }
  199. }
  200. }
  201. }