Program.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. using HealthChecks.UI.Client;
  2. using Microsoft.AspNetCore.Diagnostics.HealthChecks;
  3. using Microsoft.AspNetCore.Http.Connections;
  4. using Microsoft.AspNetCore.Http.Features;
  5. using Microsoft.AspNetCore.Server.Kestrel.Core;
  6. using Microsoft.Extensions.DependencyInjection.Extensions;
  7. using OASystem.API.HealthChecks;
  8. using OASystem.API.Middlewares;
  9. using OASystem.API.OAMethodLib;
  10. using OASystem.API.OAMethodLib.AMapApi;
  11. using OASystem.API.OAMethodLib.APNs;
  12. using OASystem.API.OAMethodLib.Hub.Hubs;
  13. using OASystem.API.OAMethodLib.JuHeAPI;
  14. using OASystem.API.OAMethodLib.QiYeWeChatAPI;
  15. using OASystem.API.OAMethodLib.Quartz.Jobs;
  16. using OASystem.API.OAMethodLib.SignalR.HubService;
  17. using Quartz;
  18. using Quartz.Impl;
  19. using Quartz.Spi;
  20. using QuzrtzJob.Factory;
  21. using Serilog.Events;
  22. Console.Title = $"FMGJ OASystem Server";
  23. var builder = WebApplication.CreateBuilder(args);
  24. var basePath = AppContext.BaseDirectory;
  25. //引入配置文件
  26. var _config = new ConfigurationBuilder()
  27. .SetBasePath(basePath)
  28. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  29. .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true)
  30. .AddEnvironmentVariables()
  31. .Build();
  32. builder.Services.AddSingleton(new AppSettingsHelper(_config));
  33. //设置请求参数可不填
  34. builder.Services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
  35. //设置请求参数错误默认返回格式
  36. builder.Services.AddControllers()
  37. .ConfigureApiBehaviorOptions(options =>
  38. {
  39. options.InvalidModelStateResponseFactory = context =>
  40. {
  41. var errors = context.ModelState
  42. .Where(e => e.Value.Errors.Count > 0)
  43. .ToDictionary(
  44. kvp => kvp.Key,
  45. kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
  46. );
  47. var result = new JsonView
  48. {
  49. Code = 400,
  50. Msg = errors.FirstOrDefault().Value.FirstOrDefault() ?? "",
  51. Data = errors
  52. };
  53. return new BadRequestObjectResult(result);
  54. };
  55. });
  56. // Add services to the container.
  57. builder.Services.AddControllersWithViews();
  58. builder.Services.AddControllers()
  59. .AddJsonOptions(options =>
  60. {
  61. //空字段不响应Response
  62. //options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
  63. options.JsonSerializerOptions.Converters.Add(new NullJsonConverter());
  64. //时间格式化响应
  65. options.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter("yyyy-MM-dd HH:mm:ss"));
  66. //decimal 四位小数
  67. //options.JsonSerializerOptions.Converters.Add(new DecimalConverter(_decimalPlaces)); // 将保留小数位数参数传递给自定义序列化器
  68. });
  69. builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  70. #region Cors
  71. builder.Services.AddCors(policy =>
  72. {
  73. //policy.AddPolicy("Cors", opt => opt
  74. //.AllowAnyOrigin()
  75. //.AllowAnyHeader()
  76. //.AllowAnyMethod()
  77. //.WithExposedHeaders("X-Pagination"));
  78. policy.AddPolicy("Cors", opt => opt
  79. .SetIsOriginAllowed(origin =>
  80. {
  81. // 定义允许的来源列表
  82. var allowedOrigins = new List<string>
  83. {
  84. "http://132.232.92.186:9002"
  85. };
  86. // 检查请求的来源是否在允许的列表中
  87. return allowedOrigins.Contains(origin);
  88. })
  89. //.AllowAnyOrigin()
  90. .AllowAnyHeader()
  91. .WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS")
  92. .AllowCredentials());
  93. });
  94. #endregion
  95. #region 上传文件
  96. builder.Services.AddCors(policy =>
  97. {
  98. policy.AddPolicy("Cors", opt => opt
  99. .AllowAnyOrigin()
  100. .AllowAnyHeader()
  101. .AllowAnyMethod()
  102. .WithExposedHeaders("X-Pagination"));
  103. });
  104. builder.Services.Configure<FormOptions>(options =>
  105. {
  106. options.KeyLengthLimit = int.MaxValue;
  107. options.ValueLengthLimit = int.MaxValue;
  108. options.MultipartBodyLengthLimit = int.MaxValue;
  109. options.MultipartHeadersLengthLimit = int.MaxValue;
  110. });
  111. builder.Services.Configure<KestrelServerOptions>(options =>
  112. {
  113. options.Limits.MaxRequestBodySize = int.MaxValue;
  114. options.Limits.MaxRequestBufferSize = int.MaxValue;
  115. });
  116. #endregion
  117. #region 接口分组
  118. var groups = new List<Tuple<string, string>>
  119. {
  120. //new Tuple<string, string>("Group1","分组一"),
  121. //new Tuple<string, string>("Group2","分组二")
  122. };
  123. #endregion
  124. #region 注入数据库
  125. builder.Services.AddScoped(options =>
  126. {
  127. return new SqlSugarClient(new List<ConnectionConfig>()
  128. {
  129. new() {
  130. ConfigId = DBEnum.OA2023DB,
  131. ConnectionString = _config.GetConnectionString("OA2023DB"),
  132. DbType = DbType.SqlServer,
  133. IsAutoCloseConnection = true
  134. },
  135. new()
  136. {
  137. ConfigId = DBEnum.OA2014DB,
  138. ConnectionString = _config.GetConnectionString("OA2014DB"),
  139. DbType = DbType.SqlServer,
  140. IsAutoCloseConnection = true },
  141. }
  142. , db =>
  143. {
  144. //SQL执行完
  145. db.Aop.OnLogExecuted = (sql, pars) =>
  146. {
  147. //if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
  148. //{
  149. //代码CS文件名
  150. var fileName = db.Ado.SqlStackTrace.FirstFileName;
  151. //代码行数
  152. var fileLine = db.Ado.SqlStackTrace.FirstLine;
  153. //方法名
  154. var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName;
  155. //执行完了可以输出SQL执行时间 (OnLogExecutedDelegate)
  156. Console.WriteLine("NowTime:" + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"));
  157. Console.WriteLine("MethodName:" + FirstMethodName);
  158. Console.WriteLine("ElapsedTime:" + db.Ado.SqlExecutionTime.ToString());
  159. Console.WriteLine("ExecuteSQL:" + sql);
  160. //}
  161. };
  162. //SQL执行前
  163. db.Aop.OnLogExecuting = (sql, pars) =>
  164. {
  165. //获取原生SQL推荐 5.1.4.63 性能OK
  166. //UtilMethods.GetNativeSql(sql, pars);
  167. //获取无参数化SQL 影响性能只适合调试
  168. //UtilMethods.GetSqlString(DbType.SqlServer,sql,pars)
  169. };
  170. //SQL报错
  171. db.Aop.OnError = (exp) =>
  172. {
  173. //获取原生SQL推荐 5.1.4.63 性能OK
  174. //UtilMethods.GetNativeSql(exp.sql, exp.parameters);
  175. //获取无参数SQL对性能有影响,特别大的SQL参数多的,调试使用
  176. //UtilMethods.GetSqlString(DbType.SqlServer, exp.sql, exp.parameters);
  177. };
  178. //修改SQL和参数的值
  179. db.Aop.OnExecutingChangeSql = (sql, pars) =>
  180. {
  181. //sql=newsql
  182. //foreach(var p in pars) //修改
  183. return new KeyValuePair<string, SugarParameter[]>(sql, pars);
  184. };
  185. }
  186. );
  187. });
  188. #endregion
  189. //#region Identity 配置
  190. //builder.Services.AddDataProtection();
  191. ////不要用 AddIdentity , AddIdentity 是于MVC框架中的
  192. //builder.Services.AddIdentityCore<User>(opt =>
  193. //{
  194. // opt.Password.RequireDigit = false; //数字
  195. // opt.Password.RequireLowercase = false;//小写字母
  196. // opt.Password.RequireNonAlphanumeric = false;//特殊符号 例如 ¥#@!
  197. // opt.Password.RequireUppercase = false; //大写字母
  198. // opt.Password.RequiredLength = 6;//密码长度 6
  199. // opt.Password.RequiredUniqueChars = 1;//相同字符可以出现几次
  200. // opt.Lockout.MaxFailedAccessAttempts = 5; //允许最多输入五次用户名/密码错误
  201. // opt.Lockout.DefaultLockoutTimeSpan = new TimeSpan(0, 5, 0);//锁定五分钟
  202. // opt.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider; // 修改密码使用邮件【验证码模式】
  203. // opt.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultEmailProvider; ////
  204. //});
  205. //var idBuilder = new IdentityBuilder(typeof(User), typeof(UserRole), services);
  206. //idBuilder.AddEntityFrameworkStores<swapDbContext>().AddDefaultTokenProviders().AddRoleManager<RoleManager<UserRole>>().AddUserManager<UserManager<User>>();
  207. //#endregion
  208. #region 注入Swagger注释(启用)
  209. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  210. {
  211. builder.Services.AddSwaggerGen(a =>
  212. {
  213. a.SwaggerDoc("v1", new OpenApiInfo
  214. {
  215. Version = "v1",
  216. Title = "Api",
  217. Description = "Api接口文档"
  218. });
  219. foreach (var item in groups)
  220. {
  221. a.SwaggerDoc(item.Item1, new OpenApiInfo { Version = item.Item1, Title = item.Item2, Description = $"{item.Item2}接口文档" });
  222. }
  223. a.DocumentFilter<SwaggerApi>();
  224. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Api.xml"), true);
  225. a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Domain.xml"), true);
  226. a.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
  227. {
  228. Description = "Value: Bearer {token}",
  229. Name = "Authorization",
  230. In = ParameterLocation.Header,
  231. Type = SecuritySchemeType.ApiKey,
  232. Scheme = "Bearer"
  233. });
  234. a.AddSecurityRequirement(new OpenApiSecurityRequirement()
  235. {{
  236. new OpenApiSecurityScheme
  237. {
  238. Reference = new OpenApiReference
  239. {
  240. Type = ReferenceType.SecurityScheme,
  241. Id = "Bearer"
  242. }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header }, new List<string>()
  243. }
  244. });
  245. });
  246. }
  247. #endregion
  248. #region 添加校验
  249. builder.Services.AddTransient<OASystemAuthentication>();
  250. builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  251. .AddJwtBearer(options =>
  252. {
  253. options.TokenValidationParameters = new TokenValidationParameters
  254. {
  255. ValidateIssuer = true,
  256. ValidateAudience = true,
  257. ValidateLifetime = true,
  258. ValidateIssuerSigningKey = true,
  259. ValidAudience = "OASystem.com",
  260. ValidIssuer = "OASystem.com",
  261. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSecurityKey"])),
  262. ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值,解决服务器端时间不同步问题(秒)
  263. RequireExpirationTime = true,
  264. };
  265. options.Events = new JwtBearerEvents
  266. {
  267. OnMessageReceived = context =>
  268. {
  269. var path = context.HttpContext.Request.Path;
  270. //如果是signalr请求,需要将token转存,否则JWT获取不到token。OPTIONS请求需要过滤到,因为OPTIONS请求获取不到Token,用NGINX过滤掉OPTION请求.
  271. if (path.StartsWithSegments("/ChatHub"))
  272. {
  273. string accessToken = context.Request.Query["access_token"].ToString();
  274. if (string.IsNullOrWhiteSpace(accessToken))
  275. {
  276. accessToken = context.Request.Headers["Authorization"].ToString();
  277. }
  278. context.Token = accessToken.Replace("Bearer ", "").Trim();
  279. }
  280. return Task.CompletedTask;
  281. }
  282. };
  283. });
  284. #endregion
  285. #region 初始化日志
  286. var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
  287. Log.Logger = new LoggerConfiguration()
  288. //不记录定时访问API
  289. .Filter.ByIncludingOnly(logEvent =>
  290. {
  291. if (logEvent.Properties.TryGetValue("RequestPath", out var pathValue))
  292. {
  293. var path = pathValue.ToString().Trim('"');
  294. return !path.StartsWith("/api/System/PotsMessageUnreadTotalCount");
  295. }
  296. return true;
  297. })
  298. .MinimumLevel.Information()
  299. .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
  300. .MinimumLevel.Override("System", LogEventLevel.Warning)
  301. .Enrich.FromLogContext()
  302. .WriteTo.Console()
  303. .WriteTo.File(Path.Combine("Logs", @"Log.txt"), rollingInterval: RollingInterval.Day)
  304. .CreateLogger();
  305. // 配置Serilog为Log;
  306. builder.Host.UseSerilog();
  307. #endregion
  308. #region 健康检查服务
  309. //// Add health checks
  310. //builder.Services.AddHealthChecks()
  311. // .AddCheck<ExampleHealthCheck>("example_health_check")
  312. // .AddCheck<DatabaseHealthCheck>("database")
  313. // .AddCheck<ApiHealthCheck>("external_api",
  314. // tags: new[] { "infrastructure" });
  315. //builder.Services.AddHealthChecksUI(options =>
  316. //{
  317. // options.AddHealthCheckEndpoint("API", "/health");
  318. // options.AddHealthCheckEndpoint("External Service", "https://other-service/health"); // 外部服务
  319. //}).AddInMemoryStorage();
  320. //builder.Services.AddEndpointsApiExplorer();
  321. #endregion
  322. #region 引入注册Autofac Module
  323. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
  324. var hostBuilder = builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
  325. {
  326. try
  327. {
  328. builder.RegisterModule(new AutofacRegister());
  329. }
  330. catch (Exception ex)
  331. {
  332. throw new Exception(ex.Message + "\n" + ex.InnerException);
  333. }
  334. });
  335. #endregion
  336. #region AutoMapper
  337. AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg =>
  338. {
  339. cfg.AddProfile<_baseMappingProfile>();
  340. });
  341. builder.Services.AddSingleton(config);
  342. builder.Services.AddScoped<IMapper, Mapper>();
  343. #endregion
  344. #region 聚合API 服务
  345. builder.Services.AddControllersWithViews();
  346. builder.Services.AddSingleton<IJuHeApiService, JuHeApiService>();
  347. builder.Services.AddHttpClient("PublicJuHeApi", c => c.BaseAddress = new Uri("http://web.juhe.cn"));
  348. builder.Services.AddHttpClient("PublicJuHeTranslateApi", c => c.BaseAddress = new Uri("http://apis.juhe.cn"));
  349. #endregion
  350. #region 企业微信API 服务
  351. builder.Services.AddControllersWithViews();
  352. builder.Services.AddSingleton<IQiYeWeChatApiService, QiYeWeChatApiService>();
  353. builder.Services.AddHttpClient("PublicQiYeWeChatApi", c => c.BaseAddress = new Uri("https://qyapi.weixin.qq.com"));
  354. #endregion
  355. #region 有道API 服务
  356. //builder.Services.AddControllersWithViews();
  357. //builder.Services.AddSingleton<IYouDaoApiService, YouDaoApiService>();
  358. //builder.Services.AddHttpClient("PublicYouDaoApi", c => c.BaseAddress = new Uri("https://openapi.youdao.com"));
  359. #endregion
  360. #region 高德地图API 服务
  361. builder.Services.AddHttpClient<GeocodeService>();
  362. #endregion
  363. #region Quartz
  364. builder.Services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
  365. builder.Services.AddSingleton<QuartzFactory>();
  366. builder.Services.AddSingleton<ALiYunPostMessageJob>();
  367. builder.Services.AddSingleton<TaskJob>();
  368. builder.Services.AddSingleton<TaskNewsFeedJob>();
  369. //# new business
  370. builder.Services.AddControllersWithViews();
  371. builder.Services.AddSingleton<IAPNsService, APNsService>();
  372. builder.Services.AddSingleton<IJobFactory, IOCJobFactory>();
  373. #endregion
  374. #region SignalR
  375. builder.Services.AddSignalR()
  376. .AddJsonProtocol(options =>
  377. {
  378. options.PayloadSerializerOptions.PropertyNamingPolicy = null;
  379. });
  380. builder.Services.TryAddSingleton(typeof(CommonService));
  381. #endregion
  382. var app = builder.Build();
  383. //自定义异常中间件
  384. app.UseMiddleware<ExceptionHandlingMiddleware>();
  385. //serilog日志 请求中间管道
  386. app.UseSerilogRequestLogging(options =>
  387. {
  388. //options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} from {ClientIP} (UA: {UserAgent}, Referer: {Referer}) - {StatusCode} in {Elapsed} ms";
  389. options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} from {ClientIP} (UA: {UserAgent}) - {StatusCode} in {Elapsed} ms";
  390. // 自定义日志级别
  391. options.GetLevel = (httpContext, elapsed, ex) =>
  392. {
  393. if (ex != null) return LogEventLevel.Error;
  394. if (httpContext.Response.StatusCode > 499) return LogEventLevel.Error;
  395. // 对健康检查等端点使用更低级别
  396. if (httpContext.Request.Path.StartsWithSegments("/health"))
  397. return LogEventLevel.Debug;
  398. return LogEventLevel.Information;
  399. };
  400. // 丰富日志上下文
  401. options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
  402. {
  403. // 获取客户端IP(处理代理情况)
  404. var ipAddress = CommonFun.GetClientIpAddress(httpContext);
  405. var userAgent = CommonFun.DetectOS(httpContext.Request.Headers.UserAgent.ToString());
  406. // 添加IP和其他有用信息到日志上下文
  407. diagnosticContext.Set("ClientIP", ipAddress);
  408. diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
  409. diagnosticContext.Set("UserAgent", userAgent);
  410. diagnosticContext.Set("Referer", httpContext.Request.Headers.Referer.ToString());
  411. // 对于API请求添加额外信息
  412. if (httpContext.Request.Path.StartsWithSegments("/api"))
  413. {
  414. diagnosticContext.Set("RequestContentType", httpContext.Request.ContentType);
  415. diagnosticContext.Set("RequestContentLength", httpContext.Request.ContentLength ?? 0);
  416. }
  417. };
  418. });
  419. AutofacIocManager.Instance.Container = app.UseHostFiltering().ApplicationServices.GetAutofacRoot();//AutofacIocManager
  420. // Configure the HTTP request pipeline.
  421. if (!app.Environment.IsDevelopment())
  422. {
  423. app.UseExceptionHandler("/Home/Error");
  424. }
  425. app.UseStaticFiles();
  426. app.UseRouting();
  427. app.UseCors("Cors"); //Cors
  428. //app.UseMiddleware<FixedPromptMiddleware>();
  429. // 定义允许API的访问时间段
  430. //var startTime = DateTime.Parse(_config["ApiAccessTime:StartTime"]);
  431. //var endTime = DateTime.Parse(_config["ApiAccessTime:EndTime"]);
  432. //app.UseMiddleware<TimeRestrictionMiddleware>(startTime, endTime);
  433. //指定API操作记录信息
  434. app.UseMiddleware<RecordAPIOperationMiddleware>();
  435. app.UseAuthentication(); // 认证
  436. app.UseAuthorization(); // 授权
  437. // 授权路径
  438. //app.MapGet("generatetoken", c => c.Response.WriteAsync(JWTBearer.GenerateToken(c)));
  439. #region 启用swaggerUI
  440. if (AppSettingsHelper.Get("UseSwagger").ToBool())
  441. {
  442. app.UseSwagger();
  443. app.UseSwaggerUI(c =>
  444. {
  445. c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ver0.1");
  446. foreach (var item in groups)
  447. {
  448. c.SwaggerEndpoint($"/swagger/{item.Item1}/swagger.json", item.Item2);
  449. }
  450. c.RoutePrefix = string.Empty;
  451. c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
  452. c.DefaultModelsExpandDepth(-1);
  453. //c.EnableFilter();// 添加搜索功能
  454. //c.EnableDeepLinking(); // 启用深度链接
  455. });
  456. }
  457. #endregion
  458. #region Quartz
  459. //获取容器中的QuartzFactory
  460. var quartz = app.Services.GetRequiredService<QuartzFactory>();
  461. app.Lifetime.ApplicationStarted.Register(async () =>
  462. {
  463. await quartz.Start();
  464. });
  465. app.Lifetime.ApplicationStopped.Register(() =>
  466. {
  467. //Quzrtz关闭方法
  468. //quartz.Stop();
  469. });
  470. #endregion
  471. #region SignalR
  472. app.MapHub<ChatHub>("/ChatHub", options =>
  473. {
  474. options.Transports =
  475. HttpTransportType.WebSockets |
  476. HttpTransportType.LongPolling;
  477. });
  478. #endregion
  479. #region 配置健康检查端点
  480. //app.MapHealthChecks("/health", new HealthCheckOptions
  481. //{
  482. // ResponseWriter = async (context, report) =>
  483. // {
  484. // var result = new
  485. // {
  486. // Status = report.Status.ToString(),
  487. // Checks = report.Entries.Select(e => new {
  488. // Name = e.Key,
  489. // Status = e.Value.Status.ToString(),
  490. // Description = e.Value.Description
  491. // }),
  492. // Duration = report.TotalDuration
  493. // };
  494. // await context.Response.WriteAsJsonAsync(result);
  495. // }
  496. //});
  497. //// 健康检查UI仪表板(可视化界面)
  498. //app.MapHealthChecksUI(options =>
  499. //{
  500. // options.UIPath = "/health-ui"; // 访问路径
  501. // options.ApiPath = "/health-ui-api"; // API路径(供UI前端调用)
  502. //});
  503. #endregion
  504. app.MapControllerRoute(
  505. name: "default",
  506. pattern: "{controller=Home}/{action=Index}/{id?}");
  507. app.Run();