-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
208 lines (176 loc) · 6.9 KB
/
Program.cs
File metadata and controls
208 lines (176 loc) · 6.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
using SoraEssayJudge.Services;
using SoraEssayJudge.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.OpenApi.Models;
using Microsoft.Extensions.FileProviders;
using System.IO;
using Serilog;
using Microsoft.AspNetCore.HttpOverrides;
using System.Net;
using SoraEssayJudge.Models;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Http.Features;
// 1. Configure Serilog for bootstrap logging
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateBootstrapLogger();
Log.Information("Starting up");
try
{
var builder = WebApplication.CreateBuilder(args);
// Increase upload size limit
builder.Services.Configure<KestrelServerOptions>(options =>
{
options.Limits.MaxRequestBodySize = 1073741824; // 1024 MB
});
builder.Services.Configure<FormOptions>(options =>
{
options.MultipartBodyLengthLimit = 1073741824; // 1024 MB
});
// 2. Add full Serilog support
builder.Host.UseSerilog((context, services, configuration) => configuration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext());
// Add services to the container.
builder.Services.AddDbContext<EssayContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")));
// 添加 CORS 服务
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
builder.Services.AddScoped<ApiKeyService>();
builder.Services.AddScoped<OpenAIService>();
builder.Services.AddScoped<RecognizeHandwritingService>();
builder.Services.AddScoped<ProcessImageService>();
builder.Services.AddScoped<JudgeService>();
builder.Services.AddScoped<IPreProcessImageService, PreProcessImageService>();
builder.Services.AddScoped<IPreProcessImageServiceV2, PreProcessImageServiceV2>();
builder.Services.AddScoped<IImageStitchingService, ImageStitchingService>();
builder.Services.AddScoped<IExcelExportService, ExcelExportService>();
builder.Services.AddHttpClient<UploadTemporaryImageService>();
builder.Services.Configure<DingTalkConfiguration>(builder.Configuration.GetSection("DingTalk"));
builder.Services.AddMemoryCache();
builder.Services.AddHttpClient<IDingTalkService, DingTalkService>();
builder.Services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles;
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(s =>
{
s.SwaggerDoc("v1", new OpenApiInfo { Title = "SoraEssayJudge Api", Version = "v1" });
s.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Description = "在下框中输入请求头中需要添加Jwt授权Token:Bearer Token",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
BearerFormat = "JWT",
Scheme = "Bearer"
});
s.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme{
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"}
},new string[] { }
}
});
});
// JWT 认证服务
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = 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.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
// 安全提示:在生产环境中,最好清除 KnownProxies 和 KnownNetworks
// 并明确指定您的代理服务器的 IP 地址,以防止 IP 欺骗。
// options.KnownProxies.Add(IPAddress.Parse("YOUR_NGINX_IP_ADDRESS"));
});
var app = builder.Build();
// 3. Add Serilog request logging middleware
app.UseSerilogRequestLogging();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseForwardedHeaders();
// 启用 CORS
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
// 确保 essayfiles 目录存在
var essayFilesPath = Path.Combine(app.Environment.ContentRootPath, "essayfiles");
if (!Directory.Exists(essayFilesPath))
{
Directory.CreateDirectory(essayFilesPath);
}
// 配置 essayfiles 目录为静态文件目录
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(essayFilesPath),
RequestPath = "/essayfiles"
});
app.UseHttpsRedirection();
app.MapControllers();
// 在应用程序启动时应用数据库迁移
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<EssayContext>();
context.Database.EnsureCreated(); // 确保数据库已创建
context.Database.Migrate(); // 应用所有待处理的迁移
Log.Information("Database migration completed successfully.");
}
catch (Exception ex)
{
Log.Error(ex, "An error occurred while migrating the database.");
// 根据需要,可以选择在这里停止应用程序或继续运行
}
}
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Unhandled exception");
}
finally
{
Log.Information("Shut down complete");
Log.CloseAndFlush();
}