WebApiHelper.cs 14 KB

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