Files
DRS9.DashboardServer/src/DRS9.Dashboard.Server/Program.cs

173 lines
5.1 KiB
C#
Raw Normal View History

2026-01-13 13:50:27 +08:00
using System.Text;
using DRS9.Dashboard.Application.Services;
using DRS9.Dashboard.Infrastructure.Data;
using DRS9.Dashboard.Server.Middleware;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
2026-01-13 17:57:48 +08:00
builder.Services.AddControllersWithViews(); // 支持 MVC 视图
builder.Services.AddRazorPages();
2026-01-13 13:50:27 +08:00
// Configure Database
builder.Services.AddDbContext<DashboardDbContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")));
// Configure JWT Authentication
var jwtKey = builder.Configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT Key not configured");
var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? throw new InvalidOperationException("JWT Issuer not configured");
var jwtAudience = builder.Configuration["Jwt:Audience"] ?? throw new InvalidOperationException("JWT Audience not configured");
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtIssuer,
ValidAudience = jwtAudience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey))
};
});
builder.Services.AddAuthorization();
// Add Blazor Server
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
2026-01-13 17:57:48 +08:00
// Add HttpContextAccessor for MVC controllers
builder.Services.AddHttpContextAccessor();
2026-01-13 13:50:27 +08:00
// Configure Blazor Server Circuit
builder.Services.AddServerSideBlazor()
.AddCircuitOptions(options =>
{
options.DetailedErrors = true;
options.DisconnectedCircuitRetentionPeriod = TimeSpan.FromMinutes(3);
});
// Register HttpClient and API Client Service
builder.Services.AddHttpClient<DRS9.Dashboard.Server.Services.ApiClientService>(client =>
{
client.BaseAddress = new Uri("http://localhost:5000");
});
// Configure CORS
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
// Register Application Services
var jwtExpiry = int.TryParse(builder.Configuration["Jwt:ExpiryMinutes"], out var expiry) ? expiry : 43200;
builder.Services.AddSingleton(new JwtTokenService(
jwtKey,
jwtIssuer,
jwtAudience,
jwtExpiry
));
builder.Services.AddScoped<DeviceService>();
builder.Services.AddScoped<ApplicationService>();
2026-01-13 17:57:48 +08:00
builder.Services.AddScoped<RotatorItemService>();
2026-01-13 13:50:27 +08:00
builder.Services.AddScoped<DeviceManagementService>();
builder.Services.AddScoped<PlaylistService>();
builder.Services.AddScoped<BatchManagementService>();
builder.Services.AddScoped<AppVersionService>();
builder.Services.AddScoped<GuestAccessService>();
builder.Services.AddSingleton<DashboardWebSocketManager>();
// Configure OpenAPI/Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddOpenApi();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "DRS9 Dashboard API",
Version = "v1",
Description = "信息发布系统 API"
});
// Add JWT Authentication to Swagger
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>()
}
});
});
var app = builder.Build();
// Initialize Database
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<DashboardDbContext>();
await DataSeeder.SeedAsync(dbContext);
}
// Configure the HTTP request pipeline.
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "DRS9 Dashboard API v1");
});
app.UseCors("AllowAll");
// 静态文件
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
// Add anti-forgery for Blazor Server
app.UseAntiforgery();
app.UseWebSockets();
app.MapControllers();
2026-01-13 17:57:48 +08:00
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
2026-01-13 13:50:27 +08:00
// Blazor Server
app.MapRazorComponents<DRS9.Dashboard.Server.Components.App>()
.AddInteractiveServerRenderMode();
// WebSocket endpoint
app.Map("/ws", app => app.UseMiddleware<WebSocketMiddleware>());
2026-01-13 15:04:30 +08:00
app.Run("http://localhost:5000");