U:调整所有代码格式

This commit is contained in:
jimmy committed 2025-12-30 09:17:25 +08:00
1 parent d133bacf55
commit 155b67e831
342 files changed
+9431 -9868

No files matched your search

@@ -48,7 +48,7 @@ public class AuthController : BaseController
var token = GenerateSimpleToken(username);
// 设置 Cookie
SetCookie(context, "auth_token", token, expiresInSeconds: 3600);
SetCookie(context, "auth_token", token, 3600);
await WriteSuccessResponseAsync(context, new
{
@@ -156,7 +156,7 @@ public class AuthController : BaseController
}
var newToken = GenerateSimpleToken(username);
SetCookie(context, "auth_token", newToken, expiresInSeconds: 3600);
SetCookie(context, "auth_token", newToken, 3600);
await WriteSuccessResponseAsync(context, new
{
@@ -199,8 +199,8 @@ public class SimpleAuthenticationProvider : IAuthenticationProvider
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Role, role)
new(ClaimTypes.Name, username),
new(ClaimTypes.Role, role)
};
var identity = new ClaimsIdentity(claims, "SimpleAuth");
@@ -216,4 +216,4 @@ public class SimpleAuthenticationProvider : IAuthenticationProvider
return Task.FromResult<ClaimsPrincipal?>(null);
}
}
}
@@ -16,7 +16,7 @@ public class ProductController : BaseController
new Product { Id = 1, Name = "笔记本电脑", Price = 5999.00m, Stock = 50, Category = "电子产品" },
new Product { Id = 2, Name = "无线鼠标", Price = 99.00m, Stock = 200, Category = "电子产品" },
new Product { Id = 3, Name = "机械键盘", Price = 399.00m, Stock = 100, Category = "电子产品" },
new Product { Id = 4, Name = "显示器", Price = 1299.00m, Stock = 30, Category = "电子产品" },
new Product { Id = 4, Name = "显示器", Price = 1299.00m, Stock = 30, Category = "电子产品" }
};
/// <summary>
@@ -109,14 +109,12 @@ public class ProductController : BaseController
var stockUpdate = await ReadJsonBodyAsync<Dictionary<string, object>>(context);
if (stockUpdate != null && stockUpdate.TryGetValue("quantity", out var quantityObj))
{
if (int.TryParse(quantityObj.ToString(), out var quantity))
{
product.Stock = quantity;
await WriteSuccessResponseAsync(context, product, "库存更新成功");
return;
}
}
await BadRequestAsync(context, "无效的库存数量");
}
@@ -190,4 +188,4 @@ public class Product
public decimal Price { get; set; }
public int Stock { get; set; }
public string Category { get; set; } = string.Empty;
}
}
@@ -168,4 +168,4 @@ public class User
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string Role { get; set; } = "User";
}
}
@@ -47,7 +47,8 @@ public class ExampleProgram
// 配置服务 - 注册认证提供者
builder.ConfigureServices(services =>
{
services.AddSingleton<Sharp.NetServer.Abstractions.IAuthenticationProvider, SimpleAuthenticationProvider>();
services
.AddSingleton<Sharp.NetServer.Abstractions.IAuthenticationProvider, SimpleAuthenticationProvider>();
});
// 启用限流 - 防止滥用
@@ -225,4 +226,4 @@ public class ExampleProgram
Console.WriteLine(" - Token 有效期: 1小时");
Console.WriteLine(" - 某些接口有限流保护");
}
}
}
@@ -142,10 +142,7 @@ public class ServerIntegrationTests
var tasks = new List<Task<HttpResponseMessage>>();
// Act - 发送 10 个并发请求
for (int i = 0; i < 10; i++)
{
tasks.Add(client.GetAsync($"api/integration/concurrent?id={i}"));
}
for (var i = 0; i < 10; i++) tasks.Add(client.GetAsync($"api/integration/concurrent?id={i}"));
var responses = await Task.WhenAll(tasks);
@@ -201,4 +198,4 @@ internal class IntegrationTestController : BaseController
await Task.Delay(50); // 模拟一些处理时间
await WriteSuccessResponseAsync(context, new { id, processed = true });
}
}
}
+2 -2
View File
@@ -22,8 +22,8 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Sharp\NetServer\NetServer.csproj" />
<ProjectReference Include="..\..\src\Sharp\Common\Common.csproj" />
<ProjectReference Include="..\..\src\Sharp\NetServer\NetServer.csproj"/>
<ProjectReference Include="..\..\src\Sharp\Common\Common.csproj"/>
</ItemGroup>
</Project>
+56 -39
View File
@@ -3,12 +3,14 @@
## 🎉 项目完成状态
### ✅ 核心框架 (Sharp.NetServer)
- **状态**: 完全实现并编译成功
- **文件数**: 26 个 C# 源文件
- **代码行数**: 约 2,578 行
- **编译状态**: ✅ 0 错误,0 警告
### ✅ 测试项目 (NetServer.Test)
- **状态**: 完全实现并测试通过
- **文件数**: 8 个 C# 源文件
- **测试数量**: 16 个测试
@@ -16,6 +18,7 @@
- **测试时间**: 6.2 秒
### 📊 总体统计
- **总文件数**: 34 个 C# 文件
- **总代码量**: 约 3,500+ 行
- **测试覆盖**: 核心功能全覆盖
@@ -27,47 +30,48 @@
### 核心组件
1. **HTTP 服务器** (`Server/`)
- HttpServer.cs - 基于 HttpListener 的服务器实现
- HttpServerOptions.cs - 服务器配置选项
- HttpServer.cs - 基于 HttpListener 的服务器实现
- HttpServerOptions.cs - 服务器配置选项
2. **路由系统** (`Routing/`)
- RouteTable.cs - 路由注册和管理
- RouteInfo.cs - 路由元数据
- RouteTable.cs - 路由注册和管理
- RouteInfo.cs - 路由元数据
3. **中间件系统** (`Middleware/`)
- MiddlewarePipeline.cs - 中间件管道
- ExceptionHandlingMiddleware.cs - 全局异常处理
- LoggingMiddleware.cs - 请求日志
- CorsMiddleware.cs - CORS 处理
- AuthenticationMiddleware.cs - 身份认证
- AuthorizationMiddleware.cs - 授权检查
- RateLimitMiddleware.cs - 限流
- ResponseCacheMiddleware.cs - 响应缓存
- MiddlewarePipeline.cs - 中间件管道
- ExceptionHandlingMiddleware.cs - 全局异常处理
- LoggingMiddleware.cs - 请求日志
- CorsMiddleware.cs - CORS 处理
- AuthenticationMiddleware.cs - 身份认证
- AuthorizationMiddleware.cs - 授权检查
- RateLimitMiddleware.cs - 限流
- ResponseCacheMiddleware.cs - 响应缓存
4. **控制器** (`Controllers/`)
- BaseController.cs - 控制器基类(提供丰富的辅助方法)
- BaseController.cs - 控制器基类(提供丰富的辅助方法)
5. **特性系统** (`Attributes/`)
- RouteAttribute.cs - 路由特性
- HttpMethodAttributes.cs - HTTP 方法特性
- AuthorizeAttribute.cs - 授权特性
- RateLimitAttribute.cs - 限流特性
- CacheAttribute.cs - 缓存特性
- CorsAttribute.cs - CORS 特性
- RouteAttribute.cs - 路由特性
- HttpMethodAttributes.cs - HTTP 方法特性
- AuthorizeAttribute.cs - 授权特性
- RateLimitAttribute.cs - 限流特性
- CacheAttribute.cs - 缓存特性
- CorsAttribute.cs - CORS 特性
6. **模型** (`Models/`)
- HttpContext.cs - HTTP 上下文封装
- ResponseModel.cs - 标准响应模型
- HttpContext.cs - HTTP 上下文封装
- ResponseModel.cs - 标准响应模型
7. **抽象接口** (`Abstractions/`)
- IMiddleware.cs - 中间件接口
- IAuthenticationProvider.cs - 认证提供者接口
- IMiddleware.cs - 中间件接口
- IAuthenticationProvider.cs - 认证提供者接口
---
## ✨ 核心功能
### 1. 特性路由系统
```csharp
[ApiController]
[Route("api/users")]
@@ -81,6 +85,7 @@ public class UserController : BaseController
```
### 2. 中间件管道
- 全局异常处理
- 请求日志记录
- CORS 支持
@@ -90,6 +95,7 @@ public class UserController : BaseController
- 自定义中间件
### 3. 限流(Rate Limiting)
```csharp
[RateLimit(100, RateLimitScope.Ip)] // 每个 IP 每分钟 100 次
[RateLimit(50, RateLimitScope.User)] // 每个用户每分钟 50 次
@@ -97,12 +103,14 @@ public class UserController : BaseController
```
### 4. 响应缓存
```csharp
[ResponseCache(60)] // 缓存 60 秒
[ResponseCache(300, VaryByQueryKeys = true)] // 根据查询参数缓存
```
### 5. 认证授权
```csharp
[Authorize] // 需要认证
[Authorize(Roles = "Admin")] // 需要角色
@@ -111,12 +119,14 @@ public class UserController : BaseController
```
### 6. CORS
```csharp
[EnableCors(Origins = "http://localhost:3000", AllowCredentials = true)]
[DisableCors]
```
### 7. 控制器辅助方法
```csharp
// 读取请求
var query = GetQueryParam(context, "name");
@@ -140,19 +150,20 @@ var value = GetCookie(context, "name");
### 单元测试
1. **路由系统测试** (7 个测试)
- 路由注册和发现
- 路由匹配
- 路径参数支持
- 特性解析
- 路由注册和发现
- 路由匹配
- 路径参数支持
- 特性解析
2. **中间件测试** (3 个测试)
- 执行顺序
- 多中间件支持
- 短路机制
- 执行顺序
- 多中间件支持
- 短路机制
### 集成测试
**服务器集成测试** (6 个测试)
- HTTP 请求处理 (GET/POST)
- 查询参数解析
- CORS 支持
@@ -212,51 +223,57 @@ curl -X POST http://localhost:5000/api/users \
### 已创建的文档
1. **框架文档**
- [README.md](../../src/Sharp/NetServer/README.md) - 快速入门和 API 文档
- [ARCHITECTURE.md](../../src/Sharp/NetServer/ARCHITECTURE.md) - 架构设计
- [README.md](../../src/Sharp/NetServer/README.md) - 快速入门和 API 文档
- [ARCHITECTURE.md](../../src/Sharp/NetServer/ARCHITECTURE.md) - 架构设计
2. **测试文档**
- [README.md](../../test/NetServer.Test/README.md) - 测试和示例说明
- [SUMMARY.md](../../test/NetServer.Test/SUMMARY.md) - 项目完成总结
- [README.md](../../test/NetServer.Test/README.md) - 测试和示例说明
- [SUMMARY.md](../../test/NetServer.Test/SUMMARY.md) - 项目完成总结
3. **代码示例**
- DemoController.cs - 基础示例
- UserController.cs - 用户管理完整示例
- ProductController.cs - 产品管理完整示例
- AuthController.cs - 认证完整示例
- ExampleProgram.cs - 可运行的完整程序
- DemoController.cs - 基础示例
- UserController.cs - 用户管理完整示例
- ProductController.cs - 产品管理完整示例
- AuthController.cs - 认证完整示例
- ExampleProgram.cs - 可运行的完整程序
---
## 🎯 项目亮点
### 1. 简单易用
- 类似 Spring Boot 的开发体验
- 基于特性的声明式配置
- 丰富的辅助方法
### 2. 功能完整
- 路由、中间件、认证、授权
- 限流、缓存、CORS
- 日志、异常处理
### 3. 高性能
- 基于 HttpListener
- 异步 I/O
- 并发请求处理
- 响应缓存
### 4. 可扩展
- 自定义中间件
- 自定义认证提供者
- 依赖注入支持
### 5. 测试完善
- 16 个自动化测试
- 完整的集成测试
- 真实业务场景示例
### 6. 文档齐全
- 详细的 API 文档
- 架构设计文档
- 使用示例和教程
+20
View File
@@ -67,14 +67,18 @@ cd bin/Debug/net8.0
### 1. 单元测试 (UnitTests/)
#### RouteTableTests.cs
测试路由系统的核心功能:
- ✅ 路由注册和发现
- ✅ 路由匹配(包括路径参数)
- ✅ 特性解析(授权、限流、缓存等)
- ✅ 无效路由处理
#### MiddlewarePipelineTests.cs
测试中间件管道:
- ✅ 中间件执行顺序
- ✅ 多个中间件的链式调用
- ✅ 中间件短路机制
@@ -82,7 +86,9 @@ cd bin/Debug/net8.0
### 2. 集成测试 (IntegrationTests/)
#### ServerIntegrationTests.cs
测试完整的服务器功能:
- ✅ HTTP GET/POST 请求处理
- ✅ 查询参数解析
- ✅ 404 错误处理
@@ -96,6 +102,7 @@ cd bin/Debug/net8.0
### 1. 用户管理示例 (UserController.cs)
展示了完整的 CRUD 操作:
- `GET /api/users` - 获取所有用户(需要 Admin 角色)
- `GET /api/users/{id}` - 获取单个用户(带缓存)
- `POST /api/users` - 创建用户(需要 Admin 角色)
@@ -104,6 +111,7 @@ cd bin/Debug/net8.0
- `GET /api/users/search` - 搜索用户(允许匿名)
**特性展示**:
- 角色授权 (`[Authorize(Roles = "Admin")]`)
- 限流保护 (`[RateLimit]`)
- 响应缓存 (`[ResponseCache]`)
@@ -112,6 +120,7 @@ cd bin/Debug/net8.0
### 2. 产品管理示例 (ProductController.cs)
展示了产品管理功能:
- `GET /api/products` - 获取所有产品(公开接口,带缓存和限流)
- `GET /api/products/{id}` - 获取产品详情(带缓存)
- `POST /api/products` - 创建产品(需要 Admin)
@@ -120,6 +129,7 @@ cd bin/Debug/net8.0
- `GET /api/products/search` - 搜索产品(支持价格范围)
**特性展示**:
- 查询参数处理
- 部分更新 (PATCH)
- 复杂搜索条件
@@ -128,6 +138,7 @@ cd bin/Debug/net8.0
### 3. 认证示例 (AuthController.cs)
展示了完整的认证流程:
- `POST /api/auth/login` - 用户登录
- `POST /api/auth/logout` - 用户登出
- `GET /api/auth/me` - 获取当前用户信息
@@ -135,6 +146,7 @@ cd bin/Debug/net8.0
- `POST /api/auth/refresh` - 刷新 Token
**特性展示**:
- 简单的 Token 认证实现
- Cookie 操作
- 密码验证
@@ -143,6 +155,7 @@ cd bin/Debug/net8.0
### 4. 完整示例程序 (ExampleProgram.cs)
一个完整的可运行示例,包含:
- ✅ 服务器配置和启动
- ✅ CORS 配置
- ✅ 认证授权配置
@@ -173,6 +186,7 @@ curl -X POST http://localhost:5000/api/auth/login \
```
响应示例:
```json
{
"success": true,
@@ -239,25 +253,30 @@ curl -X PATCH http://localhost:5000/api/products/1/stock \
## 📊 功能特性展示
### 认证授权
- ✅ 基于 Token 的认证
- ✅ Cookie 支持
- ✅ 角色验证
- ✅ 权限验证
### 限流
- ✅ 基于 IP 的限流
- ✅ 基于用户的限流
- ✅ 防暴力破解
### 缓存
- ✅ 内存响应缓存
- ✅ 基于查询参数的缓存变化
### CORS
- ✅ 跨域资源共享
- ✅ 预检请求处理
### 日志
- ✅ 请求日志记录
- ✅ 错误日志记录
- ✅ 性能监控(慢请求警告)
@@ -278,6 +297,7 @@ curl -X PATCH http://localhost:5000/api/products/1/stock \
## 🚧 扩展建议
基于这些示例,你可以:
- 添加数据库支持(Entity Framework Core)
- 实现真正的 JWT 认证
- 添加 Swagger/OpenAPI 文档
+19 -10
View File
@@ -20,6 +20,7 @@
#### 单元测试 (10 个)
**路由系统测试** (RouteTableTests.cs):
- ✅ RegisterController_ShouldDiscoverRoutes - 路由注册和发现
- ✅ FindRoute_ShouldMatchCorrectRoute - 路由匹配
- ✅ FindRoute_WithParameter_ShouldMatch - 路径参数匹配
@@ -29,6 +30,7 @@
- ✅ RegisterController_ShouldCaptureRateLimit - 限流配置捕获
**中间件管道测试** (MiddlewarePipelineTests.cs):
- ✅ Pipeline_ShouldExecuteMiddlewaresInOrder - 中间件执行顺序
- ✅ Pipeline_ShouldSupportMultipleMiddlewares - 多个中间件支持
- ✅ Pipeline_CanShortCircuit - 中间件短路机制
@@ -36,6 +38,7 @@
#### 集成测试 (6 个)
**服务器集成测试** (ServerIntegrationTests.cs):
- ✅ Server_ShouldRespondToGetRequest - GET 请求处理
- ✅ Server_ShouldHandleQueryParameters - 查询参数解析
- ✅ Server_ShouldHandlePostRequest - POST 请求处理
@@ -71,6 +74,7 @@ NetServer.Test/
### 1. 用户管理 API (UserController.cs)
提供完整的 CRUD 操作:
- `GET /api/users` - 获取所有用户 (需要 Admin 角色)
- `GET /api/users/{id}` - 获取单个用户 (带 30 秒缓存)
- `POST /api/users` - 创建用户 (需要 Admin 角色)
@@ -79,6 +83,7 @@ NetServer.Test/
- `GET /api/users/search?keyword=xxx` - 搜索用户 (公开)
**特性展示**:
- ✅ 角色授权 (`[Authorize(Roles = "Admin")]`)
- ✅ 限流 (管理员接口 10次/分钟,普通接口 50次/分钟)
- ✅ 响应缓存
@@ -94,6 +99,7 @@ NetServer.Test/
- `GET /api/products/search?q=xxx&minPrice=100&maxPrice=500` - 搜索
**特性展示**:
- ✅ 查询参数过滤
- ✅ 部分更新 (PATCH)
- ✅ 复杂搜索条件
@@ -108,6 +114,7 @@ NetServer.Test/
- `POST /api/auth/refresh` - 刷新 Token
**特性展示**:
- ✅ 简单 Token 认证实现 (可替换为 JWT)
- ✅ Cookie 支持
- ✅ 防暴力破解限流 (登录接口 10次/分钟)
@@ -116,6 +123,7 @@ NetServer.Test/
### 4. 完整示例程序 (ExampleProgram.cs)
一个完整的可运行 HTTP 服务器,展示:
- ✅ 服务器配置和启动
- ✅ CORS 配置
- ✅ 认证授权配置
@@ -200,24 +208,25 @@ curl "http://localhost:5000/api/users/search?keyword=张"
基于这些测试和示例,可以:
1. **扩展功能**:
- 添加数据库集成 (Entity Framework Core)
- 实现真正的 JWT 认证
- 添加 Swagger/OpenAPI 文档
- 添加数据库集成 (Entity Framework Core)
- 实现真正的 JWT 认证
- 添加 Swagger/OpenAPI 文档
2. **增强测试**:
- 添加性能测试
- 添加安全测试
- 提高代码覆盖率
- 添加性能测试
- 添加安全测试
- 提高代码覆盖率
3. **生产部署**:
- 配置 HTTPS
- 添加健康检查端点
- 集成分布式缓存 (Redis)
- 添加监控和日志收集
- 配置 HTTPS
- 添加健康检查端点
- 集成分布式缓存 (Redis)
- 添加监控和日志收集
## 🎓 学习价值
这个测试项目可以帮助开发者:
- 理解如何使用 Sharp.NetServer 框架
- 学习 RESTful API 设计最佳实践
- 掌握中间件、认证、授权等概念
@@ -29,10 +29,7 @@ public class MiddlewarePipelineTests
executionOrder.Add("Second-After");
});
pipeline.Use(next => async context =>
{
executionOrder.Add("Third");
});
pipeline.Use(next => async context => { executionOrder.Add("Third"); });
// Act
await pipeline.ExecuteAsync(null!); // 简化测试,不需要真实 context
@@ -53,14 +50,12 @@ public class MiddlewarePipelineTests
var pipeline = new MiddlewarePipeline();
var counter = 0;
for (int i = 0; i < 5; i++)
{
for (var i = 0; i < 5; i++)
pipeline.Use(next => async context =>
{
counter++;
await next(context);
});
}
// Act
await pipeline.ExecuteAsync(null!);
@@ -94,4 +89,4 @@ public class MiddlewarePipelineTests
// Assert
Assert.IsFalse(reachedEnd, "Pipeline should be short-circuited");
}
}
}
@@ -152,4 +152,4 @@ internal class TestController : BaseController
{
await WriteSuccessResponseAsync(context, new { message = "Limited" });
}
}
}