Skip to content

Commit ede6b15

Browse files
committed
[修改]1. 修改HTTP服务器的参数检查
1 parent b69ade1 commit ede6b15

3 files changed

Lines changed: 51 additions & 74 deletions

File tree

GameFrameX.NetWork.HTTP/HttpHandler.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public static async Task HandleRequest(HttpContext context, Func<string, BaseHtt
3131
{
3232
var ip = context.Connection.RemoteIpAddress?.ToString();
3333
string url = context.Request.PathBase + context.Request.Path;
34-
var command = context.Request.Path.ToString().Substring(GlobalSettings.ApiRootPath.Length);
34+
var command = context.Request.Path.ToString().Substring(GlobalSettings.CurrentSetting.HttpUrl.Length);
3535
var logHeader = $"[HTTPServer] TraceIdentifier:[{context.TraceIdentifier}], 来源[{ip}], url:[{url}]";
3636
LogHelper.Debug($"{logHeader},请求方式:[{context.Request.Method}]");
3737

GameFrameX.StartUp/AppStartUpByHTTPServer.cs

Lines changed: 50 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,23 @@
11
using System.Net;
22
using System.Reflection;
33
using GameFrameX.Foundation.Logger;
4-
using GameFrameX.NetWork;
5-
using GameFrameX.NetWork.Abstractions;
64
using GameFrameX.NetWork.HTTP;
7-
using GameFrameX.NetWork.Message;
8-
using GameFrameX.StartUp.Options;
9-
using GameFrameX.SuperSocket.Connection;
10-
using GameFrameX.SuperSocket.Primitives;
11-
using GameFrameX.SuperSocket.ProtoBase;
125
using GameFrameX.SuperSocket.Server;
136
using GameFrameX.SuperSocket.Server.Abstractions;
14-
using GameFrameX.SuperSocket.Server.Abstractions.Session;
157
using GameFrameX.SuperSocket.Server.Host;
16-
using GameFrameX.SuperSocket.WebSocket;
17-
using GameFrameX.SuperSocket.WebSocket.Server;
188
using GameFrameX.Utility;
19-
using GameFrameX.Utility.Extensions;
209
using GameFrameX.Utility.Setting;
2110
using Microsoft.AspNetCore.Builder;
2211
using Microsoft.AspNetCore.Diagnostics;
2312
using Microsoft.AspNetCore.Hosting;
2413
using Microsoft.AspNetCore.Http;
25-
using Microsoft.Extensions.Configuration;
2614
using Microsoft.Extensions.DependencyInjection;
2715
using Microsoft.Extensions.Hosting;
2816
using Microsoft.Extensions.Logging;
2917
using Microsoft.OpenApi.Models;
3018
using OpenTelemetry.Resources;
3119
using OpenTelemetry.Trace;
3220
using Serilog;
33-
using CloseReason = GameFrameX.SuperSocket.WebSocket.CloseReason;
3421

3522
namespace GameFrameX.StartUp;
3623

@@ -40,54 +27,40 @@ namespace GameFrameX.StartUp;
4027
public abstract partial class AppStartUpBase
4128
{
4229
/// <summary>
43-
/// 启动 HTTP 服务器
30+
/// 启动 HTTP 服务器的异步方法
4431
/// </summary>
45-
/// <param name="hostBuilder"></param>
32+
/// <param name="hostBuilder">多服务器主机构建器,用于配置和构建服务器实例</param>
4633
/// <param name="baseHandler">HTTP处理器列表,用于处理不同的HTTP请求</param>
4734
/// <param name="httpFactory">HTTP处理器工厂,根据命令标识符创建对应的处理器实例</param>
4835
/// <param name="aopHandlerTypes">AOP处理器列表,用于在HTTP请求处理前后执行额外的逻辑</param>
4936
/// <param name="minimumLevelLogLevel">日志记录的最小级别,用于控制日志输出</param>
37+
/// <exception cref="ArgumentException">当HTTP URL格式不正确时抛出</exception>
38+
/// <exception cref="NotImplementedException">当启用HTTPS但未实现时抛出</exception>
5039
private async Task StartHttpServerAsync(MultipleServerHostBuilder hostBuilder, List<BaseHttpHandler> baseHandler, Func<string, BaseHttpHandler> httpFactory, List<IHttpAopHandler> aopHandlerTypes = null, LogLevel minimumLevelLogLevel = LogLevel.Debug)
5140
{
52-
var apiRootPath = Setting.HttpUrl;
53-
// 根路径必须以/开头和以/结尾
41+
// 验证HTTP URL格式
5442
if (!Setting.HttpUrl.StartsWith('/'))
5543
{
56-
apiRootPath = "/" + Setting.HttpUrl;
44+
throw new ArgumentException("Http 地址必须以/开头", nameof(Setting.HttpUrl));
5745
}
5846

5947
if (!Setting.HttpUrl.EndsWith('/'))
6048
{
61-
apiRootPath += "/";
49+
throw new ArgumentException("Http 地址必须以/结尾", nameof(Setting.HttpUrl));
6250
}
6351

64-
GlobalSettings.ApiRootPath = apiRootPath;
65-
6652
LogHelper.InfoConsole("启动 [HTTP] 服务器...");
53+
// 检查端口是否可用
6754
if (Setting.HttpPort is > 0 and < ushort.MaxValue && NetHelper.PortIsAvailable(Setting.HttpPort))
6855
{
6956
var builder = WebApplication.CreateBuilder();
7057

58+
// 确定是否为开发环境
7159
var development = Setting.HttpIsDevelopment || builder.Environment.IsDevelopment();
7260

7361
var openApiInfo = GetOpenApiInfo();
7462

75-
// hostBuilder.AddServer(hostBuilder =>
76-
// {
77-
// hostBuilder.ConfigureServices((context, serviceCollection) =>
78-
// {
79-
// serviceCollection.Configure<ServerOptions>(options =>
80-
// {
81-
// var listenOptions = new ListenOptions()
82-
// {
83-
// Ip = "Any",
84-
// Port = Setting.WsPort,
85-
// };
86-
// options.AddListener(listenOptions);
87-
// });
88-
// });
89-
// });
90-
63+
// 在开发环境下配置Swagger
9164
if (development)
9265
{
9366
// 添加 Swagger 服务
@@ -106,17 +79,15 @@ private async Task StartHttpServerAsync(MultipleServerHostBuilder hostBuilder, L
10679
});
10780
}
10881

109-
82+
// 配置Web主机
11083
builder.WebHost.UseKestrel(options =>
11184
{
11285
options.ListenAnyIP(Setting.HttpPort);
11386

114-
// HTTPS
87+
// HTTPS配置检查
11588
if (Setting.HttpsPort > 0 && NetHelper.PortIsAvailable(Setting.HttpsPort))
11689
{
11790
throw new NotImplementedException("HTTPS 未实现,请取消HTTPS端口配置");
118-
119-
// options.ListenAnyIP(Setting.HttpsPort, listenOptions => { listenOptions.UseHttps(); });
12091
}
12192
}).ConfigureLogging(logging =>
12293
{
@@ -126,9 +97,10 @@ private async Task StartHttpServerAsync(MultipleServerHostBuilder hostBuilder, L
12697
});
12798

12899
var app = builder.Build();
100+
101+
// 开发环境下的Swagger UI配置
129102
if (development)
130103
{
131-
// 添加 Swagger 中间件
132104
app.UseSwagger();
133105
app.UseSwaggerUI(options =>
134106
{
@@ -142,9 +114,10 @@ private async Task StartHttpServerAsync(MultipleServerHostBuilder hostBuilder, L
142114
}
143115
}
144116

117+
// 配置全局异常处理
145118
app.UseExceptionHandler(ExceptionHandler);
146119

147-
// 每个http处理器,注册到路由中
120+
// 注册HTTP处理器路由
148121
foreach (var handler in baseHandler)
149122
{
150123
var handlerType = handler.GetType();
@@ -154,8 +127,11 @@ private async Task StartHttpServerAsync(MultipleServerHostBuilder hostBuilder, L
154127
continue;
155128
}
156129

157-
// 只支持POST请求
158-
var route = app.MapPost($"{apiRootPath}{mappingAttribute.StandardCmd}", async (HttpContext context, string text) => { await HttpHandler.HandleRequest(context, httpFactory, aopHandlerTypes); });
130+
// 注册POST路由
131+
var apiPath = $"{GlobalSettings.CurrentSetting.HttpUrl}{mappingAttribute.StandardCmd}";
132+
var route = app.MapPost(apiPath, async (HttpContext context, string text) => { await HttpHandler.HandleRequest(context, httpFactory, aopHandlerTypes); });
133+
134+
// 开发环境下配置API文档
159135
if (development)
160136
{
161137
// 开发模式,启用 Swagger
@@ -177,85 +153,87 @@ private async Task StartHttpServerAsync(MultipleServerHostBuilder hostBuilder, L
177153
}
178154
}
179155

180-
181156
/// <summary>
182-
/// 启动 HTTP 服务器
157+
/// 启动 HTTP 服务器的同步方法
183158
/// </summary>
184159
/// <param name="baseHandler">HTTP处理器列表,用于处理不同的HTTP请求</param>
185160
/// <param name="httpFactory">HTTP处理器工厂,根据命令标识符创建对应的处理器实例</param>
186161
/// <param name="aopHandlerTypes">AOP处理器列表,用于在HTTP请求处理前后执行额外的逻辑</param>
187162
/// <param name="minimumLevelLogLevel">日志记录的最小级别,用于控制日志输出</param>
163+
/// <exception cref="ArgumentException">当HTTP URL格式不正确时抛出</exception>
164+
/// <exception cref="NotImplementedException">当启用HTTPS但未实现时抛出</exception>
188165
private async Task StartHttpServer(List<BaseHttpHandler> baseHandler, Func<string, BaseHttpHandler> httpFactory, List<IHttpAopHandler> aopHandlerTypes = null, LogLevel minimumLevelLogLevel = LogLevel.Debug)
189166
{
190-
var apiRootPath = Setting.HttpUrl;
191-
// 根路径必须以/开头和以/结尾
167+
// 验证HTTP URL格式
192168
if (!Setting.HttpUrl.StartsWith('/'))
193169
{
194-
apiRootPath = "/" + Setting.HttpUrl;
170+
throw new ArgumentException("Http 地址必须以/开头", nameof(Setting.HttpUrl));
195171
}
196172

197173
if (!Setting.HttpUrl.EndsWith('/'))
198174
{
199-
apiRootPath += "/";
175+
throw new ArgumentException("Http 地址必须以/结尾", nameof(Setting.HttpUrl));
200176
}
201177

202-
GlobalSettings.ApiRootPath = apiRootPath;
203-
204178
LogHelper.InfoConsole("启动 [HTTP] 服务器...");
179+
// 检查端口是否可用
205180
if (Setting.HttpPort is > 0 and < ushort.MaxValue && NetHelper.PortIsAvailable(Setting.HttpPort))
206181
{
207182
var builder = WebApplication.CreateBuilder();
208183

184+
// 确定是否为开发环境
209185
var development = Setting.HttpIsDevelopment || EnvironmentHelper.IsDevelopment();
210186

211187
var openApiInfo = GetOpenApiInfo();
188+
189+
// 在开发环境下配置Swagger
212190
if (development)
213191
{
214-
// 添加 Swagger 服务
215192
builder.Services.AddEndpointsApiExplorer();
216193
builder.Services.AddSwaggerGen(options =>
217194
{
218195
options.SwaggerDoc(openApiInfo.Version, openApiInfo);
219-
220-
// 使用自定义的 SchemaFilter 来保持属性名称大小写
221196
options.SchemaFilter<PreservePropertyCasingSchemaFilter>();
222-
223-
// 添加自定义操作过滤器来处理动态路由
224197
options.OperationFilter<SwaggerOperationFilter>(baseHandler);
225-
// 使用完整的类型名称
226198
options.CustomSchemaIds(type => type.Name);
227199
});
228200
}
229201

230-
202+
// 配置Web主机
231203
builder.WebHost.UseKestrel(options =>
232204
{
233205
options.ListenAnyIP(Setting.HttpPort);
234206

235-
// HTTPS
236207
if (Setting.HttpsPort > 0 && NetHelper.PortIsAvailable(Setting.HttpsPort))
237208
{
238209
throw new NotImplementedException("HTTPS 未实现,请取消HTTPS端口配置");
239-
240-
// options.ListenAnyIP(Setting.HttpsPort, listenOptions => { listenOptions.UseHttps(); });
241210
}
242-
}).ConfigureLogging(logging =>
211+
})
212+
.ConfigureLogging(logging =>
243213
{
244214
logging.ClearProviders();
245215
logging.AddSerilog(Log.Logger);
246216
logging.SetMinimumLevel(minimumLevelLogLevel);
247217
})
218+
// 配置OpenTelemetry服务
248219
.ConfigureServices(services =>
249220
{
250221
services.AddOpenTelemetry()
251-
.ConfigureResource(configure => { configure.AddService("HTTP:" + Setting.ServerName + "-" + Setting.TagName, "GameFrameX.HTTP").AddTelemetrySdk(); })
222+
.ConfigureResource(configure =>
223+
{
224+
configure.AddService("HTTP:" + Setting.ServerName + "-" + Setting.TagName, "GameFrameX.HTTP")
225+
.AddTelemetrySdk();
226+
})
252227
.WithTracing(configure =>
253228
{
254229
configure.AddAspNetCoreInstrumentation();
255230
configure.AddConsoleExporter();
256231
});
257232
});
233+
258234
var app = builder.Build();
235+
236+
// 开发环境下的Swagger UI配置
259237
if (development)
260238
{
261239
// 添加 Swagger 中间件
@@ -272,9 +250,10 @@ private async Task StartHttpServer(List<BaseHttpHandler> baseHandler, Func<strin
272250
}
273251
}
274252

253+
// 配置全局异常处理
275254
app.UseExceptionHandler(ExceptionHandler);
276255

277-
// 每个http处理器,注册到路由中
256+
// 注册HTTP处理器路由
278257
foreach (var handler in baseHandler)
279258
{
280259
var handlerType = handler.GetType();
@@ -284,8 +263,11 @@ private async Task StartHttpServer(List<BaseHttpHandler> baseHandler, Func<strin
284263
continue;
285264
}
286265

287-
// 只支持POST请求
288-
var route = app.MapPost($"{apiRootPath}{mappingAttribute.StandardCmd}", async (HttpContext context, string text) => { await HttpHandler.HandleRequest(context, httpFactory, aopHandlerTypes); });
266+
// 注册POST路由
267+
var apiPath = $"{GlobalSettings.CurrentSetting.HttpUrl}{mappingAttribute.StandardCmd}";
268+
var route = app.MapPost(apiPath, async (HttpContext context, string text) => { await HttpHandler.HandleRequest(context, httpFactory, aopHandlerTypes); });
269+
270+
// 开发环境下配置API文档
289271
if (development)
290272
{
291273
// 开发模式,启用 Swagger

GameFrameX.Utility/Setting/GlobalSettings.cs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,6 @@ public static class GlobalSettings
3838
/// </summary>
3939
public static bool IsDebug { get; set; }
4040

41-
/// <summary>
42-
/// API根地址
43-
/// </summary>
44-
public static string ApiRootPath { get; set; }
45-
4641
/// <summary>
4742
/// 数据存储间隔 单位 毫秒,默认5分钟,最小1秒
4843
/// </summary>

0 commit comments

Comments
 (0)