151 lines
5.5 KiB
C#
151 lines
5.5 KiB
C#
|
|
|
|
using ZhiYi.Core.Application.WebSocket;
|
|
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
builder.Services.AddControllers(option =>
|
|
{
|
|
option.Filters.Add<CustomExceptionFilterAttribute>();
|
|
})
|
|
.AddJsonOptions(jsonOption =>
|
|
{
|
|
jsonOption.JsonSerializerOptions.PropertyNamingPolicy = null; //禁用小驼峰,实体返回时保持原有大小写格式
|
|
});
|
|
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
|
//grpc
|
|
builder.Services.AddGrpc();
|
|
builder.Services.AddAutoMapper(Assembly.GetExecutingAssembly());
|
|
builder.Services.AddEndpointsApiExplorer();
|
|
var startAssembly = Assembly.GetExecutingAssembly();
|
|
builder.Services.AddSwaggerGen(c =>
|
|
{
|
|
var startAssemblyName = startAssembly.GetName().Name;
|
|
if (string.IsNullOrEmpty(startAssemblyName))
|
|
throw new NullReferenceException(nameof(startAssemblyName));
|
|
|
|
var lastName = startAssemblyName.Split('.').Last();
|
|
var apiLayerXmlFilePath = Path.Combine(AppContext.BaseDirectory, $"{startAssemblyName}.xml");
|
|
var applicationContractsLayerXmlFilePath = Path.Combine(AppContext.BaseDirectory, $"{startAssemblyName.Replace($".{lastName}", ".Application.Contracts")}.xml");
|
|
var applicationLayerXmlFilePath = Path.Combine(AppContext.BaseDirectory, $"{startAssemblyName.Replace($".{lastName}", ".Application")}.xml");
|
|
c.IncludeXmlComments(apiLayerXmlFilePath, true);
|
|
if (File.Exists(applicationContractsLayerXmlFilePath))
|
|
{
|
|
c.IncludeXmlComments(applicationContractsLayerXmlFilePath, true);
|
|
}
|
|
else if (File.Exists(applicationLayerXmlFilePath))
|
|
{
|
|
c.IncludeXmlComments(applicationLayerXmlFilePath, true);
|
|
}
|
|
c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
|
|
|
|
// 添加 JWT 认证支持
|
|
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
|
|
{
|
|
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
|
|
Name = "Authorization",
|
|
In = ParameterLocation.Header,
|
|
Type = SecuritySchemeType.ApiKey,
|
|
Scheme = "Bearer"
|
|
});
|
|
c.AddSecurityRequirement(new OpenApiSecurityRequirement
|
|
{
|
|
{
|
|
new OpenApiSecurityScheme
|
|
{
|
|
Reference = new OpenApiReference
|
|
{
|
|
Type = ReferenceType.SecurityScheme,
|
|
Id = "Bearer"
|
|
}
|
|
},
|
|
Array.Empty<string>()
|
|
}
|
|
});
|
|
});
|
|
// 注册 Redis 连接
|
|
var constr = builder.Configuration["ConnectionStrings:Redis"];
|
|
builder.Services.AddSingleton<IConnectionMultiplexer>(provider =>
|
|
{
|
|
var configuration = ConfigurationOptions.Parse(constr);
|
|
return ConnectionMultiplexer.Connect(configuration);
|
|
});
|
|
builder.Services.AddSingleton<IUserAppService, UserAppService>();
|
|
builder.Services.AddSingleton<IServerAppService, ServerAppService>();
|
|
builder.Services.AddSingleton<IGroupAppService, GroupAppService>();
|
|
builder.Services.AddSingleton<ICaptchaAppService, CaptchaAppService>();
|
|
builder.Services.AddSingleton<IConnectionClientManagerService, ConnectionClientManagerService>();
|
|
builder.Services.AddScoped<CaptchaService>();
|
|
builder.Services.AddScoped<TokenService>();
|
|
builder.Configuration.AddJsonFile($"{AppContext.BaseDirectory}/appsettings.{builder.Environment.EnvironmentName}.json", true, true);
|
|
/*builder.Services.AddAutoMapper(config =>
|
|
{
|
|
config.AddProfile(new MappingProfile()); // 如果您有一个通用的配置方法
|
|
}, typeof(YourApplicationNamespace.MappingProfile).Assembly);*/
|
|
//跨域
|
|
builder.Services.AddCors(options =>
|
|
{
|
|
options.AddPolicy("AllowSpecificOrigin",
|
|
builder => builder.WithOrigins("http://localhost:8080") // 允许的源
|
|
.AllowAnyMethod() // 允许的方法
|
|
.AllowAnyHeader() // 允许的头部
|
|
.AllowCredentials()); // 允许携带凭证
|
|
});
|
|
//鉴权配置
|
|
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
|
.AddJwtBearer(options =>
|
|
{
|
|
options.TokenValidationParameters = new TokenValidationParameters
|
|
{
|
|
ValidateIssuer = true,
|
|
ValidateAudience = true,
|
|
ValidateLifetime = true,
|
|
ValidateIssuerSigningKey = true,
|
|
ValidIssuer = builder.Configuration["Jwt:Issuer"],
|
|
ValidAudience = builder.Configuration["Jwt:Audience"],
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
|
|
};
|
|
});
|
|
|
|
|
|
//日志
|
|
builder.Logging.ClearProviders();
|
|
LogManager.LoadConfiguration($"{AppContext.BaseDirectory}/nlog.config");
|
|
builder.Host.UseNLog();
|
|
var app = builder.Build();
|
|
app.UseCors("AllowSpecificOrigin");
|
|
// Configure the HTTP request pipeline.
|
|
if (app.Environment.IsDevelopment())
|
|
{
|
|
app.UseSwagger();
|
|
app.UseSwaggerUI();
|
|
}
|
|
app.MapGrpcService<CaptchaGrpcService>();
|
|
app.UseAuthentication();
|
|
//注册签名/认证中间件
|
|
app.UseMiddleware<SignatureValidationMiddleware>();
|
|
//app.UseAuthentication(appBuilder => appBuilder Disabled = true)
|
|
app.UseStaticFiles();
|
|
var serviceManger = app.Services.GetRequiredService<IConnectionClientManagerService>();
|
|
|
|
//websocket服务
|
|
|
|
var service = new HttpService();
|
|
await service.SetupAsync(new TouchSocketConfig()//加载配置
|
|
.SetListenIPHosts(6088)
|
|
.ConfigureContainer(a =>
|
|
{
|
|
a.AddConsoleLogger();
|
|
})
|
|
.ConfigurePlugins(a =>
|
|
{
|
|
a.UseWebSocket()//添加WebSocket功能
|
|
.SetWSUrl("/ws")//设置url直接可以连接。
|
|
.UseAutoPong();//当收到ping报文时自动回应pong
|
|
a.Add(new WebSocketPlugin(serviceManger));
|
|
}));
|
|
|
|
await service.StartAsync();
|
|
service.Logger.Info("websocket服务器已启动");
|
|
app.MapControllers();
|
|
app.Run();
|