using System.Text.Json; using Autofac; using Autofac.Extensions.DependencyInjection; using CustomerApi; using CustomerApi.Hubs; using CustomerHost.Extension; using CustomerHost.Middleware; using CustomerService.Customer; using JWTHelper; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Options; using MongoRepository.Config; using Newtonsoft.Json; using NLog.Extensions.Logging; using NLog.Web; using RedisHelper; using RedisService; using SharpAbp.Infrastructure.Api.Middleware; using StackExchange.Redis; Environment.SetEnvironmentVariable("SERVICE_NAME", Environment.GetEnvironmentVariable("SERVICE_NAME") ?? System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name ?? "CustomerHost"); Environment.SetEnvironmentVariable("INSTANCE_ID", Environment.GetEnvironmentVariable("INSTANCE_ID") ?? "default"); var builder = WebApplication.CreateBuilder(args); // ============================================ // ============================================ builder.Services.AddControllers() .AddApplicationPart(typeof(AssemblyMarker).Assembly) .AddControllersAsServices(); builder.Logging.AddNLog(); builder.Host.UseNLog(); builder.Services.AddControllers().AddNewtonsoftJson( option => { option.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; option.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; } ); builder.Configuration.AddJsonFile(Path.Combine("Config", "system.json"), optional: true); builder.Services.Configure(builder.Configuration.GetSection(nameof(MongoDbSettings))); builder.Services.AddSingleton(sp => sp.GetRequiredService>().Value); builder.Services.AddSingleton(); builder.Services.AddAutoMapper(typeof(CustomerService.AutoMapperConfig)); builder.Services.AddHealthChecks() .AddCheck("self", () => HealthCheckResult.Healthy(), tags: new[] { "self" }); // ============================================ // ============================================ builder.Services.AddSignalR(hubOptions => { hubOptions.MaximumReceiveMessageSize = 64 * 1024; hubOptions.StreamBufferCapacity = 512; hubOptions.ClientTimeoutInterval = TimeSpan.FromSeconds(70); hubOptions.KeepAliveInterval = TimeSpan.FromSeconds(15); }) .AddJsonProtocol() .AddStackExchangeRedis(builder.Configuration["RedisConfig:ConnectionString"], options => { options.Configuration.ChannelPrefix = RedisChannel.Literal("CustomerHub"); }); // ============================================ // ============================================ builder.Services.AddCors(options => { options.AddPolicy("Cors", policy => { policy .SetIsOriginAllowed(_ => true) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); // ============================================ // ============================================ builder.Services.AddCustomJwt(builder.Configuration); // ============================================ // ============================================ builder.Services.AddRedisCache(builder.Configuration); // ============================================ // ============================================ builder.Services.AddCap(builder.Configuration); // ============================================ // ============================================ #region Swagger builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "CustomerApi", Description = "客服服务 API 文档", Version = "v1" }); foreach (var xml in System.IO.Directory.GetFiles(AppContext.BaseDirectory, "*.xml")) { try { c.IncludeXmlComments(xml, true); } catch { } } }); #endregion builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); builder.Host.ConfigureContainer(builder => { builder.RegisterModule(); }); // ============================================ // ============================================ var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } #region Swagger app.UseSwagger(c => c.RouteTemplate = "customerswagger/{documentName}/swagger.json"); app.UseSwaggerUI(c => { c.RoutePrefix = "customerswagger"; c.SwaggerEndpoint("v1/swagger.json", "CustomerApi v1"); }); #endregion app.UseCors("Cors"); var uploadPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads"); if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } app.UseStaticFiles(new StaticFileOptions { FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")), RequestPath = "/uploads" }); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseApiLogging(); app.MapHub("/customerHub", options => { options.Transports = Microsoft.AspNetCore.Http.Connections.HttpTransportType.WebSockets; }); app.MapControllers(); app.UseGlobalExceptionHandler(); app.MapHealthChecks("/health", new HealthCheckOptions { Predicate = _ => true, ResponseWriter = async (context, report) => { context.Response.ContentType = "application/json"; var result = new { status = report.Status.ToString(), checks = report.Entries.Select(e => new { name = e.Key, status = e.Value.Status.ToString(), description = e.Value.Description, duration = e.Value.Duration.TotalMilliseconds }), totalDuration = report.TotalDuration.TotalMilliseconds }; await context.Response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(result)); } }); app.Run();