WebApiHelper.cs 14 KB

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