Files
BuYuHouDuan/CustomerSrc/CustomerHost/Program.cs
T

201 lines
6.0 KiB
C#
Raw Normal View History

2026-10-12 16:22:04 +08:00
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<MongoDbSettings>(builder.Configuration.GetSection(nameof(MongoDbSettings)));
builder.Services.AddSingleton<IMongoDbSettings>(sp => sp.GetRequiredService<IOptions<MongoDbSettings>>().Value);
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
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
2026-10-12 16:22:04 +08:00
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
builder.RegisterModule<AutofacModule>();
});
// ============================================
// ============================================
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
2026-10-12 16:22:04 +08:00
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>("/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();