WebApiHelper.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. using Autofac;
  2. using Autofac.Extensions.DependencyInjection;
  3. using Microsoft.AspNetCore.Builder;
  4. using Microsoft.AspNetCore.Hosting;
  5. using Microsoft.AspNetCore.Http;
  6. using Microsoft.AspNetCore.Http.Features;
  7. using Microsoft.AspNetCore.Mvc.ApplicationParts;
  8. using Microsoft.AspNetCore.Mvc.Controllers;
  9. using Microsoft.AspNetCore.Server.Kestrel.Core;
  10. using Microsoft.Extensions.DependencyInjection;
  11. using Microsoft.Extensions.DependencyInjection.Extensions;
  12. using Microsoft.Extensions.FileProviders;
  13. using Microsoft.Extensions.Hosting;
  14. using Microsoft.Extensions.Logging;
  15. using Microsoft.OpenApi.Models;
  16. using Newtonsoft.Json.Converters;
  17. using Newtonsoft.Json.Serialization;
  18. using Serilog;
  19. using Serilog.Extensions.Logging;
  20. using System.Diagnostics;
  21. using System.Reflection;
  22. namespace DW5S.WebApi
  23. {
  24. /// <summary>
  25. ///
  26. /// </summary>
  27. public static class WebApiHelper
  28. {
  29. private static CancellationTokenSource _cts;
  30. /// <summary>
  31. /// 启动AspNetCore WebAPI
  32. /// (如果Controller所在程序集未被代码使用,且入口Exe被发布为自包含程序,会找不到Controller)
  33. /// </summary>
  34. /// <param name="_localPort">本地端口</param>
  35. /// <param name="controllerXmlName">Controller所在程序集XML描述文档名称,默认使用入口程序生成的xml</param>
  36. /// <param name="dtoXmlName">DTO所在程序集XML描述文档,默认使用入口程序生成的xml</param>
  37. /// <param name="staticDir">要启用的静态目录预览及文件下载的目录(已经包含upload、download、logs三个目录)</param>
  38. /// <param name="prefix">使用DI注入时程序集的前缀</param>
  39. /// <exception cref="Exception"></exception>
  40. public static void Start(int _localPort, string dtoXmlName = null, string[] staticDir = null, string controllerXmlName = null, string dllKey = "DW5S")
  41. {
  42. BaseController.EnsureAssemblyLoaded();
  43. _cts = new CancellationTokenSource();
  44. if (controllerXmlName == null)
  45. controllerXmlName = $"{AppDomain.CurrentDomain.FriendlyName}.xml";
  46. if (dtoXmlName == null)
  47. dtoXmlName = $"{AppDomain.CurrentDomain.FriendlyName}.xml";
  48. List<string> listDir = new List<string>();
  49. if (staticDir != null)
  50. {
  51. listDir.AddRange(staticDir.Select(p => p.ToLower()).Distinct());
  52. }
  53. if (!listDir.Contains("upload"))
  54. {
  55. listDir.Add("upload");
  56. }
  57. if (!listDir.Contains("download"))
  58. {
  59. listDir.Add("download");
  60. }
  61. if (!listDir.Contains("logs"))
  62. {
  63. listDir.Add("logs");
  64. }
  65. staticDir = listDir.ToArray();
  66. var assemblies = AppDomain.CurrentDomain.GetAllAssemblies(dllKey);
  67. if (assemblies == null)
  68. {
  69. throw new Exception($"未扫描到包含{dllKey}字符串的程序集");
  70. }
  71. foreach (var item in assemblies)
  72. {
  73. Console.WriteLine($"已加载DI注入程序集[{item.FullName}]");
  74. }
  75. var controllerAssemblies = assemblies.Where(p => p.GetTypes().Any(q =>
  76. {
  77. if (q.Name.EndsWith("Controller") && q.IsSubclassOf(typeof(BaseController)))
  78. return true;
  79. return false;
  80. })).ToList();
  81. if (controllerAssemblies == null || !controllerAssemblies.Any())
  82. {
  83. throw new Exception("未找到Controller所在的程序集");
  84. }
  85. var builder = WebApplication.CreateBuilder();
  86. builder.Services.AddRouting(t => t.LowercaseUrls = true);//全部路由默认显示小写
  87. #region 请求大小限制200MB及Http2支持
  88. builder.WebHost.ConfigureKestrel(options =>
  89. {
  90. options.Limits.MaxRequestBodySize = 200 << 20;//200MB
  91. options.ListenAnyIP(Convert.ToInt32(_localPort), listenOptions =>
  92. {
  93. listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
  94. });
  95. });
  96. builder.Services.Configure<FormOptions>(options =>
  97. {
  98. options.MultipartBodyLengthLimit = 200 << 20;//通过表单上传最大200MB
  99. });
  100. #endregion
  101. #region 初始化日志
  102. //取消默认的日志Provider
  103. builder.Logging.ClearProviders();
  104. builder.Host.UseSerilog((builderContext, config) =>
  105. {
  106. var basePath = AppContext.BaseDirectory;
  107. var outputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff}[线程={ThreadId}][{Level:u3}]{Message:lj}{NewLine}\t{Exception}";
  108. config.Enrich.FromLogContext()
  109. .Enrich.With(new SerilogEnricher())
  110. .WriteTo.Console(outputTemplate: outputTemplate)
  111. .WriteTo.Logger(p => p.Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Information)
  112. .WriteTo.File(Path.Combine(basePath, "Logs", "Info", ".log"), rollingInterval: Serilog.RollingInterval.Day, outputTemplate: outputTemplate))
  113. .WriteTo.Logger(p => p.Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Warning)
  114. .WriteTo.File(Path.Combine(basePath, "Logs", "Warning", ".log"), rollingInterval: Serilog.RollingInterval.Day, outputTemplate: outputTemplate))
  115. .WriteTo.Logger(p => p.Filter.ByIncludingOnly(e => e.Level == Serilog.Events.LogEventLevel.Error)
  116. .WriteTo.File(Path.Combine(basePath, "Logs", "Error", ".log"), rollingInterval: Serilog.RollingInterval.Day, outputTemplate: outputTemplate));
  117. });
  118. builder.Logging.AddSerilog();
  119. #endregion
  120. #region 启用静态文件缓存和压缩(已屏蔽,采集文件压缩率不高)
  121. //builder.Services.AddResponseCaching();
  122. //builder.Services.AddResponseCompression();
  123. #endregion
  124. #region 注入常用服务
  125. //系统缓存,可以其它地方使用IMemoryCache接口
  126. builder.Services.AddMemoryCache();
  127. //http上下文
  128. builder.Services.AddSingleton<IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
  129. //HttpClient
  130. builder.Services.AddHttpClient();//IHttpClientFactory
  131. builder.Services.AddGrpc();
  132. //builder.Services.AddGrpcClient<object>(p=>
  133. //{
  134. // p.Address = new Uri("http://127.0.0.1:16001");
  135. //}).ConfigureChannel(p =>
  136. //{
  137. //});
  138. builder.Services.AddEndpointsApiExplorer();
  139. builder.Services.AddSwaggerGen(c =>
  140. {
  141. c.SwaggerDoc("v1", new OpenApiInfo
  142. {
  143. Version = "v1",
  144. Title = $"{Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule.FileName)}Http接口文档",
  145. });
  146. var basePath = AppDomain.CurrentDomain.BaseDirectory;
  147. var xmlPath = Path.Combine(basePath, controllerXmlName);//Controller xml
  148. c.IncludeXmlComments(xmlPath, true);
  149. xmlPath = Path.Combine(basePath, "Ips.Library.WebApi.xml");//BaesController xml
  150. c.IncludeXmlComments(xmlPath, true);
  151. c.OrderActionsBy(o => o.RelativePath);
  152. xmlPath = Path.Combine(basePath, dtoXmlName);//dto xml
  153. c.IncludeXmlComments(xmlPath);
  154. });
  155. #endregion
  156. #region 注入Controller、Service、Repository、HostedService
  157. //让Controller的实例由autofac创建,而不是由dotnet框架创建,以便在控制器中使用autofac高级功能
  158. builder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
  159. //将框架默认IOC容器替换为Autofac容器
  160. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
  161. var hostBuilder = builder.Host.ConfigureContainer<Autofac.ContainerBuilder>(builder =>
  162. {
  163. //瞬态注入Controllerer,每次接口请求都创建了新的对象
  164. builder.RegisterAssemblyTypes(assemblies)
  165. .Where(type => type.Name.EndsWith("Controller"))
  166. .PropertiesAutowired((propInfo, instance) =>//Controller中的属性支持自动注入
  167. propInfo.Name.EndsWith("Autowired") || //以Autowired名称结尾的属性自动注入
  168. propInfo.GetCustomAttribute<AutowiredAttribute>() != null)//带有Autowired特性的属性自动注入
  169. .AsSelf()//接口的默认实现
  170. .InstancePerDependency();
  171. //单例注入以Service或Repository结尾的类(有继承的类不会注入)
  172. builder.RegisterAssemblyTypes(assemblies)
  173. .Where(type =>
  174. {
  175. if (!type.Name.EndsWith("Service") && !type.Name.EndsWith("Repository"))
  176. {
  177. return false;
  178. }
  179. if (type.BaseType != typeof(object))
  180. {
  181. return false;
  182. }
  183. return true;
  184. })
  185. .PropertiesAutowired((propInfo, instance) =>//Service中的属性支持自动注入
  186. propInfo.Name.EndsWith("Autowired") || //以Autowired名称结尾的属性自动注入
  187. propInfo.GetCustomAttribute<AutowiredAttribute>() != null)//带有Autowired特性的属性自动注入
  188. .AsSelf()//接口的默认实现
  189. .SingleInstance();
  190. //注入后台服务
  191. builder.RegisterAssemblyTypes(assemblies)
  192. .Where(type => type.Name.EndsWith("Service") && type.IsSubclassOf(typeof(BackgroundService)))
  193. .PropertiesAutowired((propInfo, instance) =>//BackgroundService类中的属性支持自动注入
  194. propInfo.Name.EndsWith("Autowired") || //以Autowired名称结尾的属性自动注入
  195. propInfo.GetCustomAttribute<AutowiredAttribute>() != null)//带有Autowired特性的属性自动注入
  196. .As<IHostedService>()//后台服务方式注入
  197. .InstancePerDependency();
  198. });
  199. #endregion
  200. #region 注入HostedService后台服务(已屏蔽,在后面使用了autofac自动注入)
  201. //builder.Services.AddHostedService<UploadClearService>();//执行初始化等操作
  202. #endregion
  203. builder.Services.AddControllers(c =>
  204. {
  205. //过滤器
  206. //c.Filters.Add<LogActionFilter>();
  207. })
  208. //这种方式不方便加载Controller分布在不同dll中的情况,因此使用了ConfigureApplicationPartManager
  209. //.AddApplicationPart(controllerAssemblies.First())
  210. .ConfigureApplicationPartManager(apm =>
  211. {
  212. foreach (var item in controllerAssemblies)
  213. {
  214. var part = new AssemblyPart(item);
  215. apm.ApplicationParts.Add(part);
  216. }
  217. })
  218. .AddNewtonsoftJson(options =>
  219. {
  220. //修改属性名称的序列化方式,首字母小写
  221. options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  222. //修改时间的序列化方式
  223. options.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
  224. });
  225. var app = builder.Build();
  226. #region 启用静态资源访问
  227. foreach (var item in staticDir)
  228. {
  229. //静态文件物理路径
  230. if (string.IsNullOrWhiteSpace(item)) continue;
  231. string path;
  232. if (item.Contains(":"))
  233. path = item;//绝对路径
  234. else
  235. path = Path.Combine(AppContext.BaseDirectory, item);//相对路径
  236. Directory.CreateDirectory(path);
  237. //静态资源缓存时间(300秒,600秒)
  238. var cachePeriod = app.Environment.IsDevelopment() ? "300" : "600";
  239. //启用静态文件路由
  240. app.UseStaticFiles(new StaticFileOptions
  241. {
  242. ServeUnknownFileTypes = true,
  243. FileProvider = new PhysicalFileProvider(path),
  244. RequestPath = $"/{Path.GetFileName(item)}",
  245. OnPrepareResponse = ctx =>
  246. {
  247. ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}");
  248. }
  249. });
  250. //启用目录浏览所有文件
  251. app.UseDirectoryBrowser(new DirectoryBrowserOptions()
  252. {
  253. FileProvider = new PhysicalFileProvider(path),
  254. RequestPath = $"/{Path.GetFileName(item)}"
  255. });
  256. }
  257. app.UseResponseCaching();
  258. #endregion
  259. //app.MapGrpcService<FileService>();
  260. app.Urls.Add($"http://+:{_localPort}");
  261. app.UseSwagger();
  262. app.UseSwaggerUI(c =>
  263. {
  264. c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1版本");
  265. });
  266. app.UseExceptionHandler("/Home/Error");
  267. //app.UseAuthentication();//身份验证
  268. app.UseAuthorization(); //授权
  269. //app.UseMiddleware<ExceptionHandlingMiddleware>();//全局异常处理
  270. app.MapControllers();
  271. //app.Map("/", () => "必须通过GRPC客户端访问此接口");
  272. app.RunAsync(_cts.Token);
  273. }
  274. /// <summary>
  275. /// 结束WebAPI
  276. /// </summary>
  277. public static void Stop()
  278. {
  279. _cts?.Cancel();
  280. }
  281. }
  282. }