This commit is contained in:
jimmy committed 2025-11-14 16:56:57 +08:00
1 parent 237cbd8788
commit ab3721912d
102 files changed
+7929 -20

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
# Repository Guidelines
## Project Structure & Module Organization
- Solution: `Sharp.sln` aggregates all modules in this folder.
- Libraries: `Common`, `Config`, `Log`, `EventBus`, `Sharp.Infrastructure`.
- Networking: `NetServer` (HTTP server + middleware), `NetClient` (typed HTTP client).
- UI: `Wpf` (shared WPF helpers), `Client` (WPF app using `Wpf`).
- Examples: `NetServer/Examples` contains a runnable sample entry point.
- Tests: solution includes external projects under `../../test/*` (e.g., `Common.Test`, `NetClient.Test`).
## Build, Test, and Development Commands
- Restore: `dotnet restore`
- Build (Debug/Release): `dotnet build Sharp.sln -c Debug` | `-c Release`
- Run server example: `dotnet run --project NetServer/NetServer.csproj`
- Run WPF client (Windows): `dotnet run --project Client/Client.csproj`
- Run all tests: `dotnet test Sharp.sln -c Debug --no-build`
- Run a single test project: `dotnet test ../../test/Common.Test/Common.Test.csproj`
## Coding Style & Naming Conventions
- Language/TFM: C# on .NET 8 (`net8.0` / `net8.0-windows`). Indent with 4 spaces.
- Names: `PascalCase` for public types/members; `camelCase` for locals/private fields; prefix interfaces with `I` (e.g., `IAuthenticationProvider`); suffix async methods with `Async`.
- Namespaces: use `Sharp.<Module>` (e.g., `Sharp.NetServer`). Keep folders aligned with domains (e.g., `Handlers`, `Options`, `Models`, `Middleware`).
- Formatting: run `dotnet format` before committing (install if needed: `dotnet tool install -g dotnet-format`).
## Testing Guidelines
- Framework: MSTest (solution references `*.Test` projects).
- Conventions: name files `*Tests.cs`; use clear method names like `Method_State_Expected`.
- Execution: prefer `dotnet test Sharp.sln` from this directory; for iterative work, run the relevant test project directly.
- Aim to cover critical paths in `Common`, `NetClient`, and `NetServer`, including error cases.
## Commit & Pull Request Guidelines
- History shows short messages (often Chinese, e.g., `A:...`). Keep messages concise and imperative.
- Preferred formats: `feat(scope): summary` or `模块: 简述` when appropriate.
- PRs must include: summary of changes, affected modules, linked issues, test evidence (`dotnet build`/`dotnet test` output), and screenshots for UI changes.
## Agent-Specific Notes
- Scope: this AGENTS.md applies to `src/Sharp` and its subtree.
- Keep changes minimal and consistent with existing patterns; avoid breaking public APIs without discussion.
- Place new code in the closest matching module/folder; mirror existing naming and structure.
+19
View File
@@ -0,0 +1,19 @@
using System.Windows;
using Sharp.Wpf.Exceptions;
namespace Client;
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var handler = new UiExceptionHandler();
handler.Register(new ExceptionHandlingOptions
{
ShowDialog = true,
DialogTitle = "应用程序错误"
});
}
}
+52 -3
View File
@@ -1,6 +1,12 @@
using System.Configuration;
using System.Data;
using System;
using System.Windows;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Common;
using Config;
using NetClient.DependencyInjection;
using Sharp.Log.Extensions;
using Sharp.NetServer.DependencyInjection;
namespace Client
{
@@ -9,6 +15,49 @@ namespace Client
/// </summary>
public partial class App : Application
{
}
private ServiceProvider? _serviceProvider;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// 1) Build configuration manager from appsettings.json (+ reload on change + env vars)
var cm = ConfigBuilder.BuildFromFiles(new[] { "appsettings.json" }, reloadOnChange: true, includeEnvironment: true, basePath: AppContext.BaseDirectory);
// 2) Build DI container
var services = new ServiceCollection();
// ConfigManager and typed SystemConfig accessor
services.AddSingleton(cm);
services.AddSystemConfig(cm);
// Logging (binds from section "SharpLog")
services.AddLogging(b => b.AddSharpLog());
// Net modules from configuration
services.AddNetClient(cm);
services.AddNetServer(cm);
// WPF app services
_serviceProvider = services.BuildServiceProvider();
// 3) Register global facades for convenience
Global.RegisterSingleton(_serviceProvider);
Global.RegisterSingleton(cm);
Global.RegisterSingleton(_serviceProvider.GetRequiredService<ISystemConfigAccessor>());
// 4) Show main window
var main = new MainWindow
{
DataContext = new ViewModels.MainViewModel()
};
main.Show();
}
protected override void OnExit(ExitEventArgs e)
{
_serviceProvider?.Dispose();
base.OnExit(e);
}
}
}
@@ -0,0 +1,43 @@
using System;
using System.Threading.Tasks;
using System.Windows.Input;
using Sharp.Wpf.Commands;
using Sharp.Wpf.Mvvm;
using Sharp.Wpf.Services;
namespace Client.ViewModels;
public sealed class MainViewModel : ViewModelBase
{
private readonly IDialogService _dialog = new DialogService();
private string _greeting = "欢迎使用 Sharp.Wpf";
public string Greeting
{
get => _greeting;
set => SetProperty(ref _greeting, value);
}
public IAsyncCommand ShowDialogCommand { get; }
public ICommand ThrowCommand { get; }
public MainViewModel()
{
ShowDialogCommand = new AsyncCommand(async () =>
{
try
{
IsBusy = true;
await Task.Delay(300);
await _dialog.ShowInfoAsync("Hello from Sharp.Wpf DialogService!");
Greeting = $"时间: {DateTime.Now:HH:mm:ss}";
}
finally
{
IsBusy = false;
}
});
ThrowCommand = new RelayCommand(() => throw new InvalidOperationException("演示:未处理异常将被全局处理"));
}
}
+53
View File
@@ -0,0 +1,53 @@
{
"System": {
"HTTPIp": "127.0.0.1",
"HttpPort": 8080,
"TimeoutSeconds": 30,
"Scheme": "http"
},
"NetServer": {
"UseLogging": true,
"UseExceptionHandling": true,
"UseCors": true,
"UseRateLimit": true,
"UseResponseCache": true
},
"NetClient": {
"Timeout": "00:00:20",
"EnableLogging": true,
"IncludeCorrelationId": true,
"CorrelationIdHeaderName": "X-Correlation-Id",
"UseBearerToken": false,
"Retry": {
"Enabled": true,
"MaxRetryAttempts": 3,
"FirstDelay": "00:00:01",
"Handle429": true,
"HandleRequestTimeout": true
}
},
"SharpLog": {
"UseSerilog": true,
"UseConsole": true,
"ConsoleJson": false,
"MinLevel": "Information",
"Overrides": {
"Microsoft": "Warning"
},
"File": {
"Enabled": true,
"Path": "logs/app-.log",
"Rolling": "Day",
"RetainedFileCountLimit": 7,
"Json": true
},
"Enrich": {
"Enabled": true,
"WithThreadId": true,
"WithProcessId": true,
"WithMachineName": true,
"WithEnvironmentName": true,
"WithActivityTrace": true
}
}
}
@@ -0,0 +1,71 @@
#pragma checksum "..\..\..\App.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "878B875A6A09A9568F92EC16A87C1A2A9A208AA0"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using Client;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Controls.Ribbon;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms.Integration;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace Client {
/// <summary>
/// App
/// </summary>
public partial class App : System.Windows.Application {
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "9.0.4.0")]
public void InitializeComponent() {
#line 5 "..\..\..\App.xaml"
this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative);
#line default
#line hidden
}
/// <summary>
/// Application Entry Point.
/// </summary>
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "9.0.4.0")]
public static void Main() {
Client.App app = new Client.App();
app.InitializeComponent();
app.Run();
}
}
}
@@ -0,0 +1,79 @@
#pragma checksum "..\..\..\MainWindow.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "BEEAE53C9D96DFAC0315F07E3682D21B80792BEB"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using Client;
using Sharp.Wpf.Behaviors;
using Sharp.Wpf.Converters;
using Sharp.Wpf.Windowing;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Controls.Ribbon;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms.Integration;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace Client {
/// <summary>
/// MainWindow
/// </summary>
public partial class MainWindow : System.Windows.Window, System.Windows.Markup.IComponentConnector {
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "9.0.4.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/Client;component/mainwindow.xaml", System.UriKind.Relative);
#line 1 "..\..\..\MainWindow.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "9.0.4.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
this._contentLoaded = true;
}
}
}
@@ -0,0 +1,45 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Config;
public interface ISystemConfigAccessor
{
SystemConfig Value { get; }
}
internal sealed class SystemConfigAccessor : ISystemConfigAccessor, IDisposable
{
private readonly ConfigManager _cm;
private readonly IDisposable _subscription;
private SystemConfig _current;
public SystemConfigAccessor(ConfigManager cm)
{
_cm = cm;
_current = cm.Get<SystemConfig>(section: "System", validate: false);
_subscription = cm.OnReload(() =>
{
// Reload on change
_current = _cm.Get<SystemConfig>(section: "System", validate: false);
});
}
public SystemConfig Value => _current;
public void Dispose() => _subscription.Dispose();
}
public static class SystemConfigExtensions
{
/// <summary>
/// Registers SystemConfig accessor backed by ConfigManager under the "System" section.
/// </summary>
public static IServiceCollection AddSystemConfig(this IServiceCollection services, ConfigManager cm)
{
services.TryAddSingleton(cm);
services.TryAddSingleton<ISystemConfigAccessor, SystemConfigAccessor>();
return services;
}
}
+22
View File
@@ -0,0 +1,22 @@
using System.ComponentModel.DataAnnotations;
namespace Config;
/// <summary>
/// Global system-level configuration, shared across modules.
/// </summary>
public sealed class SystemConfig
{
[Required]
[RegularExpression(@"^([0-9]{1,3}\.){3}[0-9]{1,3}$|^localhost$|^[a-zA-Z0-9_.-]+$")]
public string HTTPIp { get; set; } = "127.0.0.1";
[Range(1, 65535)]
public int HttpPort { get; set; } = 8080;
[Range(1, 600)]
public int TimeoutSeconds { get; set; } = 30;
public string Scheme { get; set; } = "http";
}
+7
View File
@@ -0,0 +1,7 @@
namespace EventBus
{
public class Class1
{
}
}
+101
View File
@@ -0,0 +1,101 @@
# Sharp.Log
面向“快速集成”的日志整合层:基于 `Microsoft.Extensions.Logging` 抽象,内置 Serilog 预设,实现一行接入,默认即用(Console + 按日滚动文件,结构化 JSON,丰富上下文)。
- 目标:不重造日志框架,仅做预设与桥接,减少样板代码
- 适用:控制台应用、Worker、ASP.NET Core(含中间件)
## 特性
- 一行集成:`builder.Logging.AddSharpLog()`,无配置也可用
- 输出:Console(可彩色)、文件(按日滚动、保留数量、异步写)
- 结构化:文本模板/JSON;支持模板+参数与异常详情
- 上下文丰富:`Application/Environment/Machine/Process/Thread/TraceId/SpanId`
- 过滤:全局最小级别与按分类覆盖
- ASP.NET:`UseSharpRequestLogging()` 统一请求日志(开始/结束/异常)
- 配置驱动:支持 `appsettings.json:SharpLog` 与环境变量绑定
## 快速开始
1) 引用项目(或 NuGet 包)
2) 在应用入口添加一行:
```csharp
// 控制台/Worker 通用
var host = Host.CreateDefaultBuilder(args)
.ConfigureLogging(b => b.AddSharpLog())
.Build();
// ASP.NET Core
var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddSharpLog(); // 一行集成
var app = builder.Build();
app.UseSharpRequestLogging(); // 可选:请求日志
app.Run();
```
无需任何 `appsettings.json`,即可获得:
- Console 文本输出
- 文件 JSON 输出:`logs/app-.log`(按天滚动,保留 30 个文件,异步写)
- 丰富上下文属性
## 可选配置(appsettings.json)
```json
{
"SharpLog": {
"UseSerilog": true,
"UseConsole": true,
"ConsoleJson": false,
"MinLevel": "Information",
"Overrides": {
"Microsoft": "Warning",
"System": "Warning"
},
"File": {
"Enabled": true,
"Path": "logs/app-.log",
"Rolling": "Day",
"RetainedFileCountLimit": 30,
"FileSizeLimitBytes": null,
"Buffered": true,
"Shared": false,
"Json": true
},
"Enrich": {
"Enabled": true,
"WithThreadId": true,
"WithProcessId": true,
"WithMachineName": true,
"WithEnvironmentName": true,
"Application": null,
"WithActivityTrace": true
}
}
}
```
环境变量示例:
- `SHARPLOG__MINLEVEL=Warning`
- `SHARPLOG__FILE__RETAINEDFILECOUNTLIMIT=7`
## API 概览
- `ILoggingBuilder AddSharpLog(Action<SharpLogOptions>? configure = null)`
- `IApplicationBuilder UseSharpRequestLogging()`
- 选项:`SharpLogOptions`、`FileOptions`、`EnrichOptions`、`RollingInterval`
## 常见问题
- 需要清空默认 Provider 吗?
- 如需仅使用 Sharp.Log,请在调用方执行 `builder.Logging.ClearProviders()`,然后 `AddSharpLog()`。
- 一定要 Serilog 吗?
- 默认启用(文件/JSON/丰富器等依赖)。如不想使用,可在配置中设置 `UseSerilog=false`,保留框架自带 Console(建议不要 `ClearProviders()`)。
- 与分布式追踪兼容吗?
- 兼容。自动注入 `Activity.TraceId/SpanId`;若使用 OpenTelemetry,日志会带 Trace 关联信息。
## 目录
- `Options/` 选项模型
- `Internal/` Serilog 配置与 Enricher
- `Extensions/` 集成扩展
- `Middleware/` 请求日志中间件
```
日志要简单可靠:一行接入,默认即用,可配更强。
```
+120
View File
@@ -0,0 +1,120 @@
# 使用说明
本指南说明如何在不同类型项目中以“最少代码”集成 Sharp.Log,并按需进行配置与扩展。
## 1. 控制台/Worker 应用
```csharp
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Sharp.Log.Extensions;
var host = Host.CreateDefaultBuilder(args)
.ConfigureLogging(b => b.AddSharpLog()) // 一行集成,默认 Console + 文件(JSON)
.Build();
var logger = host.Services.GetRequiredService<ILogger<Program>>();
logger.LogInformation("Hello from Sharp.Log");
await host.RunAsync();
```
## 2. ASP.NET Core 应用
```csharp
using Sharp.Log.Extensions;
using Sharp.Log.Middleware;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddSharpLog(); // 一行集成
var app = builder.Build();
app.UseSharpRequestLogging(); // 可选:自动请求日志
app.MapGet("/", () => Results.Ok("ok"));
app.Run();
```
## 3. 可选配置(appsettings.json)
添加 `SharpLog` 配置节(可省略)。
```json
{
"SharpLog": {
"MinLevel": "Information",
"Overrides": { "Microsoft": "Warning" },
"UseSerilog": true,
"UseConsole": true,
"ConsoleJson": false,
"File": {
"Enabled": true,
"Path": "logs/app-.log",
"Rolling": "Day",
"RetainedFileCountLimit": 30,
"Json": true
},
"Enrich": {
"Enabled": true,
"WithThreadId": true,
"WithProcessId": true,
"WithMachineName": true,
"WithEnvironmentName": true,
"WithActivityTrace": true
}
}
}
```
环境变量覆盖示例:
- `SHARPLOG__MINLEVEL=Warning`
- `SHARPLOG__FILE__PATH=/var/logs/app-.log`
- `SHARPLOG__FILE__RETAINEDFILECOUNTLIMIT=7`
## 4. 常见定制
- 仅文件输出(关闭 Console):
```csharp
builder.Logging.AddSharpLog(o => { o.UseConsole = false; });
```
- 只文本不 JSON(文件):
```csharp
builder.Logging.AddSharpLog(o => { o.File.Json = false; });
```
- 提升最小级别到 Warning:
```csharp
builder.Logging.AddSharpLog(o => { o.MinLevel = LogLevel.Warning; });
```
- 指定应用名(默认读取入口程序集名):
```csharp
builder.Logging.AddSharpLog(o => { o.Enrich.Application = "MyApp"; });
```
## 5. 与现有 Provider 协作
- 默认不清空 Provider;若希望仅用 Sharp.Log,可在应用中先执行 `ClearProviders()` 再调用 `AddSharpLog()`。
- 如将 `UseSerilog` 设为 `false`,不会注入 Serilog Provider,请保留框架自带 Console Provider(不要 `ClearProviders()`)。
## 6. 请求日志中间件
启用后会记录:请求开始、结束(状态码与耗时)、异常。
```csharp
app.UseSharpRequestLogging();
```
## 7. 结构化与上下文
日志条目自动包含:
- `Application`、`Environment`、`MachineName`、`ProcessId`、`ThreadId`
- `TraceId`、`SpanId`(来自 `Activity.Current`)
你可使用 `BeginScope` 传入业务上下文:
```csharp
using var scope = logger.BeginScope(new Dictionary<string, object>{ ["UserId"] = userId });
logger.LogInformation("User {UserId} logged in", userId);
```
## 8. 测试建议
- 在测试中为文件输出设置临时目录:
```csharp
builder.Logging.AddSharpLog(o =>
{
o.UseConsole = false;
o.File.Path = Path.Combine(tempDir, "app-.log");
o.File.Json = false;
});
```
如需更多示例,请参考本仓库的测试项目 `test/Log.Test`。
@@ -0,0 +1,47 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using Config;
using NetClient.Options;
namespace NetClient.DependencyInjection;
public static class ConfigurationExtensions
{
/// <summary>
/// Bind NetClientOptions from ConfigManager (section "NetClient").
/// Falls back to SystemConfig for BaseAddress/Timeout when not supplied.
/// </summary>
public static IServiceCollection AddNetClient(this IServiceCollection services, ConfigManager cm, string section = "NetClient")
{
var opt = cm.Get<NetClientOptions>(section, validate: false) ?? new NetClientOptions();
var sys = cm.Get<SystemConfig>("System", validate: false);
if (opt.BaseAddress is null)
{
var baseUrl = $"{sys.Scheme}://{sys.HTTPIp}:{sys.HttpPort}";
opt.BaseAddress = new Uri(baseUrl);
}
if (opt.Timeout.TotalSeconds <= 0)
{
opt.Timeout = TimeSpan.FromSeconds(Math.Max(1, sys.TimeoutSeconds));
}
// Delegate to existing AddNetClient(Action<NetClientOptions>)
services.AddNetClient(o =>
{
o.BaseAddress = opt.BaseAddress;
o.Timeout = opt.Timeout;
o.DefaultRequestHeaders = opt.DefaultRequestHeaders;
o.EnableLogging = opt.EnableLogging;
o.IncludeCorrelationId = opt.IncludeCorrelationId;
o.CorrelationIdHeaderName = opt.CorrelationIdHeaderName;
o.UseBearerToken = opt.UseBearerToken;
o.Retry = opt.Retry;
o.JsonSerializerOptions = opt.JsonSerializerOptions;
});
return services;
}
}
+115
View File
@@ -0,0 +1,115 @@
# NetClient 模块
面向 .NET 8 的轻量级 HttpClient 封装,提供:
- 统一接口 `IHttpClient`:GET/POST/PUT/PATCH/DELETE、Multipart 上传、原始 `SendAsync`
- 可选的日志、关联 ID、Bearer Token 认证
- Polly 重试策略(网络瞬时错误、5xx、可选 429/408)
- DI 一键集成:Typed Client 或 Named Client + 工厂
- 深度集成 Common 模块:统一 Result<T> 返回、默认 JsonHelper 选项
## 安装与依赖
本模块只修改当前目录,引用的包:
- Microsoft.Extensions.Http, Microsoft.Extensions.Http.Polly
- Microsoft.Extensions.Logging.Abstractions
- Polly, Polly.Extensions.Http, Polly.Contrib.WaitAndRetry
## 快速上手(Typed Client)
```csharp
using Microsoft.Extensions.DependencyInjection;
using NetClient.DependencyInjection;
using NetClient.Abstractions;
var services = new ServiceCollection();
// 可选:实现 IAccessTokenProvider 以启用 Bearer Token
services.AddSingleton<IAccessTokenProvider, MyTokenProvider>();
services.AddNetClient(opt =>
{
opt.BaseAddress = new Uri("https://api.example.com");
opt.DefaultRequestHeaders["Accept"] = "application/json";
opt.Timeout = TimeSpan.FromSeconds(30);
opt.EnableLogging = true;
opt.IncludeCorrelationId = true;
opt.UseBearerToken = true; // 若上面注册了 IAccessTokenProvider
opt.Retry.MaxRetryAttempts = 3;
});
var sp = services.BuildServiceProvider();
var client = sp.GetRequiredService<IHttpClient>();
// 调用示例
var dto = await client.GetAsync<MyDto>("/v1/items", new { page = 1, size = 20 });
var created = await client.PostAsync<CreateReq, Item>("/v1/items", new CreateReq { Name = "A" });
await client.DeleteAsync("/v1/items/123");
```
## 多服务场景(Named Client + 工厂)
```csharp
using Microsoft.Extensions.DependencyInjection;
using NetClient.DependencyInjection;
using NetClient.Abstractions;
var services = new ServiceCollection();
services.AddNamedNetClient("catalog", opt =>
{
opt.BaseAddress = new Uri("https://catalog.example.com");
opt.EnableLogging = true;
});
services.AddNamedNetClient("order", opt =>
{
opt.BaseAddress = new Uri("https://order.example.com");
opt.UseBearerToken = true;
});
var sp = services.BuildServiceProvider();
var factory = sp.GetRequiredService<INetClientFactory>();
var catalog = factory.Create("catalog");
var order = factory.Create("order");
var items = await catalog.GetAsync<ItemDto[]>("/items");
var detail = await order.GetAsync<OrderDto>("/orders/10001");
```
## Multipart 上传
```csharp
await client.PostMultipartAsync<UploadResult>("/files", form =>
{
form.Add(new StreamContent(fileStream), "file", fileName);
form.Add(new StringContent("comment"), "comment");
});
```
## 自定义序列化
默认使用 `System.Text.Json` Web 约定,可通过替换 DI 中的 `IHttpContentSerializer` 实现自定义。
```csharp
services.AddSingleton<IHttpContentSerializer>(sp =>
new MySerializer(/* options */));
```
## 错误处理
非 2xx 会抛出 `ApiException`,包含 `StatusCode` 与响应内容(若可读取)。
如偏好非异常风格,可使用 Result 版本 API:
```csharp
using Common.Results;
var ok = await client.GetResultAsync<MyDto>("/v1/items/1");
if (ok.IsSuccess) { var dto = ok.Value; }
else { Console.WriteLine(ok.ErrorCode + ":" + ok.ErrorMessage); }
```
## 何时用 Named vs Typed
- 单一后端:使用 `AddNetClient` 注册一个 Typed `IHttpClient` 即可。
- 多后端/多配置:用 `AddNamedNetClient` 注册多个名称,再通过 `INetClientFactory.Create(name)` 获取。
+166
View File
@@ -0,0 +1,166 @@
# Sharp.NetServer 项目结构
## 📁 目录结构
```
NetServer/
├── Abstractions/ # 接口定义
│ ├── IMiddleware.cs # 中间件接口
│ └── IAuthenticationProvider.cs # 认证提供者接口
│
├── Attributes/ # 特性定义
│ ├── RouteAttribute.cs # 路由特性
│ ├── HttpMethodAttributes.cs # HTTP 方法特性
│ ├── AuthorizeAttribute.cs # 授权特性
│ ├── RateLimitAttribute.cs # 限流特性
│ ├── CacheAttribute.cs # 缓存特性
│ └── CorsAttribute.cs # CORS 特性
│
├── Controllers/ # 控制器基类
│ └── BaseController.cs # 控制器基类(提供辅助方法)
│
├── Examples/ # 示例代码
│ ├── DemoController.cs # 示例控制器
│ └── Program.cs # 示例启动程序
│
├── Extensions/ # 扩展方法
│ └── ServiceCollectionExtensions.cs # DI 扩展
│
├── Middleware/ # 中间件实现
│ ├── MiddlewarePipeline.cs # 中间件管道
│ ├── ExceptionHandlingMiddleware.cs # 异常处理
│ ├── LoggingMiddleware.cs # 日志记录
│ ├── CorsMiddleware.cs # CORS 处理
│ ├── AuthenticationMiddleware.cs # 认证
│ ├── RateLimitMiddleware.cs # 限流
│ └── ResponseCacheMiddleware.cs # 响应缓存
│
├── Models/ # 模型定义
│ ├── HttpContext.cs # HTTP 上下文封装
│ └── ResponseModel.cs # 标准响应模型
│
├── Routing/ # 路由系统
│ ├── RouteInfo.cs # 路由信息
│ └── RouteTable.cs # 路由表
│
├── Server/ # 服务器核心
│ ├── HttpServer.cs # HTTP 服务器主类
│ └── HttpServerOptions.cs # 服务器配置选项
│
├── HttpServerBuilder.cs # 服务器构建器
├── NetServer.csproj # 项目文件
└── README.md # 项目文档
```
## 🔧 核心组件说明
### 1. HTTP 服务器 (Server/)
**HttpServer.cs**
- 基于 `HttpListener` 的 HTTP 服务器实现
- 管理中间件管道和路由表
- 处理请求的并发执行
- 支持依赖注入
**HttpServerOptions.cs**
- 服务器配置选项类
- 支持 Fluent API 配置
- 管理中间件和控制器程序集
### 2. 路由系统 (Routing/)
**RouteTable.cs**
- 路由注册和管理
- 基于特性的路由发现
- 路由匹配(支持路径参数)
- 路由元数据收集
**RouteInfo.cs**
- 路由信息数据模型
- 包含授权、限流、缓存等配置
### 3. 中间件系统 (Middleware/)
**执行顺序:**
1. ExceptionHandling → 全局异常处理
2. Logging → 请求日志
3. CORS → 跨域处理
4. Authentication → 身份认证
5. Authorization → 授权检查
6. RateLimit → 限流
7. ResponseCache → 响应缓存
8. Custom Middlewares → 自定义中间件
9. Route Handler → 路由处理
### 4. 控制器 (Controllers/)
**BaseController.cs**
提供以下辅助方法:
- 请求读取:`GetQueryParam()`, `ReadJsonBodyAsync()`
- 响应写入:`WriteJsonResponseAsync()`, `WriteSuccessResponseAsync()`
- 快速响应:`NotFoundAsync()`, `UnauthorizedAsync()`
- Cookie 操作:`SetCookie()`, `GetCookie()`
### 5. 特性系统 (Attributes/)
- **路由特性**: `[Route]`, `[HttpGet]`, `[HttpPost]`, etc.
- **授权特性**: `[Authorize]`, `[AllowAnonymous]`
- **限流特性**: `[RateLimit]`
- **缓存特性**: `[ResponseCache]`
- **CORS 特性**: `[EnableCors]`, `[DisableCors]`
## 🚀 使用流程
```
1. 创建 HttpServerBuilder
↓
2. 配置监听地址 (UseUrls)
↓
3. 添加控制器 (AddControllers)
↓
4. 启用中间件 (UseCors, UseAuthentication, etc.)
↓
5. 配置服务 (ConfigureServices)
↓
6. 构建服务器 (Build)
↓
7. 启动服务器 (StartAsync)
```
## 🎯 设计原则
1. **简单易用** - 类似 Spring Boot 的开发体验
2. **特性驱动** - 通过特性声明式配置
3. **中间件管道** - 灵活的请求处理流程
4. **依赖注入** - 集成 Microsoft.Extensions.DependencyInjection
5. **类型安全** - 强类型的路由和控制器
6. **可扩展性** - 支持自定义中间件和认证提供者
## 📊 性能特性
- ✅ 异步 I/O - 所有操作都是异步的
- ✅ 并发处理 - 自动处理并发请求
- ✅ 响应缓存 - 减少重复计算
- ✅ 限流保护 - 防止滥用和过载
- ✅ 轻量级 - 基于 HttpListener,无额外依赖
## 🔐 安全特性
- ✅ 认证授权 - 灵活的认证和授权机制
- ✅ CORS 支持 - 防止跨域攻击
- ✅ 限流 - 防止 DDoS 和滥用
- ✅ 异常处理 - 全局异常捕获,避免信息泄露
- ✅ 参数验证 - 控制器级别的参数验证
## 📝 待实现功能
- [ ] WebSocket 支持
- [ ] 静态文件服务
- [ ] 文件上传/下载
- [ ] Swagger/OpenAPI 文档生成
- [ ] 请求/响应压缩
- [ ] 健康检查端点
- [ ] 分布式缓存支持
- [ ] 更复杂的路由匹配(正则表达式等)
- [ ] 请求验证(基于 Data Annotations)
- [ ] 性能监控和指标收集
@@ -0,0 +1,30 @@
using System.Security.Claims;
namespace Sharp.NetServer.Abstractions;
/// <summary>
/// 身份验证提供者接口
/// </summary>
public interface IAuthenticationProvider
{
/// <summary>
/// 验证请求并返回用户身份信息
/// </summary>
Task<ClaimsPrincipal?> AuthenticateAsync(string? token);
}
/// <summary>
/// Token 提供者接口
/// </summary>
public interface ITokenProvider
{
/// <summary>
/// 生成 Token
/// </summary>
string GenerateToken(ClaimsPrincipal principal);
/// <summary>
/// 验证 Token
/// </summary>
ClaimsPrincipal? ValidateToken(string token);
}
@@ -0,0 +1,19 @@
using Sharp.NetServer.Models;
namespace Sharp.NetServer.Abstractions;
/// <summary>
/// 中间件接口
/// </summary>
public interface IMiddleware
{
/// <summary>
/// 处理请求
/// </summary>
Task InvokeAsync(HttpContext context, Func<Task> next);
}
/// <summary>
/// 中间件委托
/// </summary>
public delegate Task RequestDelegate(HttpContext context);
@@ -0,0 +1,31 @@
namespace Sharp.NetServer.Attributes;
/// <summary>
/// 授权特性 - 要求请求必须经过身份验证
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class AuthorizeAttribute : Attribute
{
/// <summary>
/// 所需角色(逗号分隔)
/// </summary>
public string? Roles { get; set; }
/// <summary>
/// 所需策略
/// </summary>
public string? Policy { get; set; }
/// <summary>
/// 所需权限(逗号分隔)
/// </summary>
public string? Permissions { get; set; }
}
/// <summary>
/// 允许匿名访问特性 - 跳过身份验证
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class AllowAnonymousAttribute : Attribute
{
}
@@ -0,0 +1,49 @@
namespace Sharp.NetServer.Attributes;
/// <summary>
/// 缓存策略
/// </summary>
public enum CacheStrategy
{
/// <summary>
/// 内存缓存
/// </summary>
Memory,
/// <summary>
/// 分布式缓存
/// </summary>
Distributed
}
/// <summary>
/// 响应缓存特性 - 缓存响应结果
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class ResponseCacheAttribute : Attribute
{
/// <summary>
/// 缓存持续时间(秒)
/// </summary>
public int Duration { get; }
/// <summary>
/// 缓存策略
/// </summary>
public CacheStrategy Strategy { get; set; } = CacheStrategy.Memory;
/// <summary>
/// 是否根据查询参数生成不同的缓存键
/// </summary>
public bool VaryByQueryKeys { get; set; } = true;
/// <summary>
/// 自定义缓存键(支持占位符,如 {userId})
/// </summary>
public string? CacheKey { get; set; }
public ResponseCacheAttribute(int duration)
{
Duration = duration;
}
}
@@ -0,0 +1,41 @@
namespace Sharp.NetServer.Attributes;
/// <summary>
/// CORS 特性 - 配置跨域资源共享
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class EnableCorsAttribute : Attribute
{
/// <summary>
/// 允许的来源(逗号分隔,* 表示全部)
/// </summary>
public string Origins { get; set; } = "*";
/// <summary>
/// 允许的方法(逗号分隔,* 表示全部)
/// </summary>
public string Methods { get; set; } = "*";
/// <summary>
/// 允许的头部(逗号分隔,* 表示全部)
/// </summary>
public string Headers { get; set; } = "*";
/// <summary>
/// 是否允许凭证
/// </summary>
public bool AllowCredentials { get; set; } = false;
/// <summary>
/// 预检请求缓存时间(秒)
/// </summary>
public int MaxAge { get; set; } = 3600;
}
/// <summary>
/// 禁用 CORS 特性
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class DisableCorsAttribute : Attribute
{
}
@@ -0,0 +1,73 @@
namespace Sharp.NetServer.Attributes;
/// <summary>
/// HTTP 方法特性基类
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public abstract class HttpMethodAttribute : Attribute
{
public string Method { get; }
public string? Template { get; }
protected HttpMethodAttribute(string method, string? template = null)
{
Method = method;
Template = template;
}
}
/// <summary>
/// HTTP GET 特性
/// </summary>
public class HttpGetAttribute : HttpMethodAttribute
{
public HttpGetAttribute(string? template = null) : base("GET", template) { }
}
/// <summary>
/// HTTP POST 特性
/// </summary>
public class HttpPostAttribute : HttpMethodAttribute
{
public HttpPostAttribute(string? template = null) : base("POST", template) { }
}
/// <summary>
/// HTTP PUT 特性
/// </summary>
public class HttpPutAttribute : HttpMethodAttribute
{
public HttpPutAttribute(string? template = null) : base("PUT", template) { }
}
/// <summary>
/// HTTP DELETE 特性
/// </summary>
public class HttpDeleteAttribute : HttpMethodAttribute
{
public HttpDeleteAttribute(string? template = null) : base("DELETE", template) { }
}
/// <summary>
/// HTTP PATCH 特性
/// </summary>
public class HttpPatchAttribute : HttpMethodAttribute
{
public HttpPatchAttribute(string? template = null) : base("PATCH", template) { }
}
/// <summary>
/// HTTP HEAD 特性
/// </summary>
public class HttpHeadAttribute : HttpMethodAttribute
{
public HttpHeadAttribute(string? template = null) : base("HEAD", template) { }
}
/// <summary>
/// HTTP OPTIONS 特性
/// </summary>
public class HttpOptionsAttribute : HttpMethodAttribute
{
public HttpOptionsAttribute(string? template = null) : base("OPTIONS", template) { }
}
@@ -0,0 +1,62 @@
namespace Sharp.NetServer.Attributes;
/// <summary>
/// 限流范围
/// </summary>
public enum RateLimitScope
{
/// <summary>
/// 全局限流
/// </summary>
Global,
/// <summary>
/// 基于 IP 地址限流
/// </summary>
Ip,
/// <summary>
/// 基于用户限流
/// </summary>
User,
/// <summary>
/// 基于端点限流
/// </summary>
Endpoint
}
/// <summary>
/// 限流特性 - 限制请求频率
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class RateLimitAttribute : Attribute
{
/// <summary>
/// 时间窗口内允许的最大请求数
/// </summary>
public int MaxRequests { get; }
/// <summary>
/// 时间窗口(秒)
/// </summary>
public int WindowSeconds { get; }
/// <summary>
/// 限流范围
/// </summary>
public RateLimitScope Scope { get; }
/// <summary>
/// 构造函数
/// </summary>
/// <param name="maxRequests">允许的最大请求数</param>
/// <param name="scope">限流范围</param>
/// <param name="windowSeconds">时间窗口(秒),默认 60 秒</param>
public RateLimitAttribute(int maxRequests, RateLimitScope scope = RateLimitScope.Ip, int windowSeconds = 60)
{
MaxRequests = maxRequests;
Scope = scope;
WindowSeconds = windowSeconds;
}
}
@@ -0,0 +1,23 @@
namespace Sharp.NetServer.Attributes;
/// <summary>
/// 路由特性 - 定义控制器或方法的路由前缀
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class RouteAttribute : Attribute
{
public string Template { get; }
public RouteAttribute(string template)
{
Template = template.StartsWith('/') ? template : "/" + template;
}
}
/// <summary>
/// API 控制器特性 - 标记类为 API 控制器
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ApiControllerAttribute : Attribute
{
}
@@ -0,0 +1,183 @@
using System.Text;
using Common.Utils;
using Sharp.NetServer.Models;
using Sharp.NetServer.Extensions;
namespace Sharp.NetServer.Controllers;
/// <summary>
/// 控制器基类 - 提供常用的辅助方法
/// </summary>
public abstract class BaseController
{
/// <summary>
/// 获取查询参数
/// </summary>
protected string GetQueryParam(HttpContext context, string key, string defaultValue = "")
{
var value = context.Request.QueryString[key];
return string.IsNullOrEmpty(value) ? defaultValue : value;
}
/// <summary>
/// 获取请求头
/// </summary>
protected string GetHeader(HttpContext context, string key, string defaultValue = "")
{
var value = context.Request.Headers[key];
return string.IsNullOrEmpty(value) ? defaultValue : value;
}
/// <summary>
/// 读取请求体为字符串
/// </summary>
protected async Task<string> ReadRequestBodyAsync(HttpContext context)
{
if (!context.Request.HasEntityBody)
return string.Empty;
using var reader = new StreamReader(context.Request.InputStream, Encoding.UTF8);
return await reader.ReadToEndAsync();
}
/// <summary>
/// 读取请求体并反序列化为对象
/// </summary>
protected async Task<T?> ReadJsonBodyAsync<T>(HttpContext context)
{
var json = await ReadRequestBodyAsync(context);
if (string.IsNullOrWhiteSpace(json))
return default;
return JsonHelper.FromJson<T>(json);
}
/// <summary>
/// 写入 JSON 响应
/// </summary>
protected async Task WriteJsonResponseAsync<T>(HttpContext context, T data, int statusCode = 200)
{
context.Response.StatusCode = statusCode;
context.Response.ContentType = "application/json; charset=utf-8";
var json = JsonHelper.ToJson(data, useCompact: true);
var bytes = Encoding.UTF8.GetBytes(json);
context.Response.ContentLength = bytes.Length;
await context.Response.OutputStream.WriteAsync(bytes);
}
/// <summary>
/// 写入文本响应
/// </summary>
protected async Task WriteTextResponseAsync(HttpContext context, string text, int statusCode = 200, string contentType = "text/plain")
{
context.Response.StatusCode = statusCode;
context.Response.ContentType = $"{contentType}; charset=utf-8";
var bytes = Encoding.UTF8.GetBytes(text);
context.Response.ContentLength = bytes.Length;
await context.Response.OutputStream.WriteAsync(bytes);
}
/// <summary>
/// 写入 HTML 响应
/// </summary>
protected async Task WriteHtmlResponseAsync(HttpContext context, string html, int statusCode = 200)
{
await WriteTextResponseAsync(context, html, statusCode, "text/html");
}
/// <summary>
/// 写入错误响应
/// </summary>
protected async Task WriteErrorResponseAsync(HttpContext context, string message, int statusCode = 500, long? errorCode = null)
{
var response = ResultExtensions.HttpFailure<object>(message, errorCode);
await WriteJsonResponseAsync(context, response, statusCode);
}
/// <summary>
/// 写入成功响应
/// </summary>
protected async Task WriteSuccessResponseAsync<T>(HttpContext context, T data, string? message = null)
{
var response = ResultExtensions.HttpSuccess(data, message);
await WriteJsonResponseAsync(context, response);
}
/// <summary>
/// 重定向
/// </summary>
protected void Redirect(HttpContext context, string url, bool permanent = false)
{
context.Response.StatusCode = permanent ? 301 : 302;
context.Response.Redirect(url);
}
/// <summary>
/// 返回 404
/// </summary>
protected async Task NotFoundAsync(HttpContext context, string? message = null)
{
await WriteErrorResponseAsync(context, message ?? "Resource not found", 404);
}
/// <summary>
/// 返回 401
/// </summary>
protected async Task UnauthorizedAsync(HttpContext context, string? message = null)
{
await WriteErrorResponseAsync(context, message ?? "Unauthorized", 401);
}
/// <summary>
/// 返回 403
/// </summary>
protected async Task ForbiddenAsync(HttpContext context, string? message = null)
{
await WriteErrorResponseAsync(context, message ?? "Forbidden", 403);
}
/// <summary>
/// 返回 400
/// </summary>
protected async Task BadRequestAsync(HttpContext context, string? message = null)
{
await WriteErrorResponseAsync(context, message ?? "Bad request", 400);
}
/// <summary>
/// 设置 Cookie
/// </summary>
protected void SetCookie(HttpContext context, string name, string value, int? expiresInSeconds = null)
{
var cookie = new System.Net.Cookie(name, value);
if (expiresInSeconds.HasValue)
{
cookie.Expires = DateTime.UtcNow.AddSeconds(expiresInSeconds.Value);
}
context.Response.Cookies.Add(cookie);
}
/// <summary>
/// 获取 Cookie
/// </summary>
protected string? GetCookie(HttpContext context, string name)
{
var cookie = context.Request.Cookies[name];
return cookie?.Value;
}
/// <summary>
/// 删除 Cookie
/// </summary>
protected void DeleteCookie(HttpContext context, string name)
{
var cookie = new System.Net.Cookie(name, "")
{
Expires = DateTime.UtcNow.AddDays(-1)
};
context.Response.Cookies.Add(cookie);
}
}
@@ -0,0 +1,29 @@
using Config;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Sharp.NetServer.Server;
namespace Sharp.NetServer.DependencyInjection;
public static class ServiceCollectionExtensions
{
/// <summary>
/// Adds HttpServerOptions bound from ConfigManager (section "NetServer").
/// If no ListenUrls specified, uses SystemConfig to build a default base URL.
/// </summary>
public static IServiceCollection AddNetServer(this IServiceCollection services, ConfigManager cm, string section = "NetServer")
{
var options = cm.Get<HttpServerOptions>(section, validate: false) ?? new HttpServerOptions();
var sys = cm.Get<SystemConfig>("System", validate: false);
if (options.ListenUrls == null || options.ListenUrls.Count == 0)
{
var baseUrl = $"{sys.Scheme}://{sys.HTTPIp}:{sys.HttpPort}/";
options.ListenUrls = new List<string> { baseUrl.EndsWith('/') ? baseUrl : baseUrl + "/" };
}
services.TryAddSingleton(options);
return services;
}
}
@@ -0,0 +1,111 @@
using Sharp.NetServer.Attributes;
using Sharp.NetServer.Controllers;
using Sharp.NetServer.Models;
namespace Sharp.NetServer.Examples;
/// <summary>
/// 示例控制器 - 演示基本用法
/// </summary>
[ApiController]
[Route("api/demo")]
[Authorize] // 类级别默认要求认证
public class DemoController : BaseController
{
/// <summary>
/// 问候接口:允许匿名访问,并限制每个 IP 每分钟 120 次
/// GET /api/demo/hello?name=Tom
/// </summary>
[AllowAnonymous]
[RateLimit(120, RateLimitScope.Ip)]
[HttpGet("hello")]
public async Task HelloAsync(HttpContext context)
{
try
{
var name = GetQueryParam(context, "name", "世界");
await WriteSuccessResponseAsync(context, new { greeting = $"你好, {name}!" });
}
catch (Exception ex)
{
await WriteErrorResponseAsync(context, $"问候失败: {ex.Message}", 500);
}
}
/// <summary>
/// 获取用户信息:需要认证
/// GET /api/demo/user
/// </summary>
[HttpGet("user")]
public async Task GetUserInfoAsync(HttpContext context)
{
var userName = context.User?.Identity?.Name ?? "未知用户";
await WriteSuccessResponseAsync(context, new
{
userName,
isAuthenticated = context.User?.Identity?.IsAuthenticated ?? false
});
}
/// <summary>
/// 创建数据:需要认证,并限制每个用户每分钟 10 次
/// POST /api/demo/data
/// Body: { "value": "test" }
/// </summary>
[HttpPost("data")]
[RateLimit(10, RateLimitScope.User)]
public async Task CreateDataAsync(HttpContext context)
{
var requestData = await ReadJsonBodyAsync<Dictionary<string, string>>(context);
if (requestData == null || !requestData.ContainsKey("value"))
{
await BadRequestAsync(context, "Missing 'value' field");
return;
}
await WriteSuccessResponseAsync(context, new
{
id = Guid.NewGuid(),
value = requestData["value"],
createdAt = DateTime.UtcNow
}, "Data created successfully");
}
/// <summary>
/// 缓存示例:响应会被缓存 60 秒
/// GET /api/demo/cached?id=123
/// </summary>
[AllowAnonymous]
[HttpGet("cached")]
[ResponseCache(60, VaryByQueryKeys = true)]
public async Task GetCachedDataAsync(HttpContext context)
{
var id = GetQueryParam(context, "id", "0");
// 模拟耗时操作
await Task.Delay(100);
await WriteSuccessResponseAsync(context, new
{
id,
timestamp = DateTime.UtcNow,
message = "This response is cached for 60 seconds"
});
}
/// <summary>
/// CORS 示例
/// GET /api/demo/cors
/// </summary>
[AllowAnonymous]
[HttpGet("cors")]
[EnableCors(Origins = "http://localhost:3000", AllowCredentials = true)]
public async Task CorsExampleAsync(HttpContext context)
{
await WriteSuccessResponseAsync(context, new
{
message = "CORS enabled for this endpoint"
});
}
}
+98
View File
@@ -0,0 +1,98 @@
using Microsoft.Extensions.Logging;
using Sharp.NetServer;
namespace Sharp.NetServer.Examples;
/// <summary>
/// 示例启动程序
/// </summary>
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("===========================================");
Console.WriteLine(" Sharp.NetServer - HTTP 服务器示例");
Console.WriteLine("===========================================");
Console.WriteLine();
// 创建服务器构建器
var builder = new HttpServerBuilder();
// 配置监听地址
builder.UseUrls("http://localhost:5000/");
// 添加控制器
builder.AddControllers(typeof(Program).Assembly);
// 启用 CORS
builder.UseCors(options =>
{
options.AllowAnyOrigin = true;
options.AllowedMethods = new[] { "GET", "POST", "PUT", "DELETE", "OPTIONS" };
options.AllowedHeaders = new[] { "Content-Type", "Authorization" };
});
// 启用认证和授权(可选)
// builder.UseAuthentication();
// builder.UseAuthorization();
// 启用限流
builder.UseRateLimit();
// 启用响应缓存
builder.UseResponseCache();
// 配置日志(需要添加 Microsoft.Extensions.Logging.Console 包)
// builder.ConfigureLogging(services =>
// {
// services.AddLogging(logging =>
// {
// logging.AddConsole();
// logging.SetMinimumLevel(LogLevel.Information);
// });
// });
// 添加自定义中间件示例
builder.UseMiddleware(next => async context =>
{
// 请求前
var startTime = DateTime.UtcNow;
await next(context);
// 请求后
var duration = (DateTime.UtcNow - startTime).TotalMilliseconds;
Console.WriteLine($"[Custom] Request processed in {duration:F2}ms");
});
// 构建服务器
var server = builder.Build();
Console.WriteLine("正在启动服务器...");
Console.WriteLine();
// 启动服务器(在后台线程启动)
var cts = new CancellationTokenSource();
_ = Task.Run(async () => await server.StartAsync(cts.Token), cts.Token);
Console.WriteLine("服务器已启动!");
Console.WriteLine();
Console.WriteLine("可用的 API 端点:");
Console.WriteLine(" GET http://localhost:5000/api/demo/hello?name=Tom");
Console.WriteLine(" GET http://localhost:5000/api/demo/user (需要认证)");
Console.WriteLine(" POST http://localhost:5000/api/demo/data (需要认证)");
Console.WriteLine(" GET http://localhost:5000/api/demo/cached?id=123");
Console.WriteLine(" GET http://localhost:5000/api/demo/cors");
Console.WriteLine();
Console.WriteLine("按任意键停止服务器...");
Console.ReadKey();
Console.WriteLine();
Console.WriteLine("正在停止服务器...");
cts.Cancel();
server.Stop();
Console.WriteLine("服务器已停止。");
}
}
@@ -0,0 +1,94 @@
using Common.Results;
namespace Sharp.NetServer.Extensions;
/// <summary>
/// Result 扩展方法 - 适配 HTTP 响应
/// </summary>
public static class ResultExtensions
{
/// <summary>
/// 转换为 HTTP 响应对象(添加时间戳)
/// </summary>
public static HttpResult<T> ToHttpResult<T>(this Result<T> result)
{
return new HttpResult<T>(result);
}
/// <summary>
/// 创建成功的 HTTP 响应
/// </summary>
public static HttpResult<T> HttpSuccess<T>(T value, string? message = null)
{
var result = Result.Success(value);
return new HttpResult<T>(result, message ?? "Success");
}
/// <summary>
/// 创建失败的 HTTP 响应
/// </summary>
public static HttpResult<T> HttpFailure<T>(string errorMessage, long? errorCode = null)
{
var result = errorCode.HasValue
? Result.Failure<T>(errorCode.Value, errorMessage)
: Result.Failure<T>(errorMessage);
return new HttpResult<T>(result);
}
/// <summary>
/// 创建失败的 HTTP 响应
/// </summary>
public static HttpResult<T> HttpFailure<T>(Exception exception)
{
var result = Result.Failure<T>(exception);
return new HttpResult<T>(result);
}
}
/// <summary>
/// HTTP 响应结果包装器 - 基于 Result,添加 HTTP 特有字段
/// </summary>
public class HttpResult<T>
{
private readonly Result<T> _result;
public HttpResult(Result<T> result, string? customMessage = null)
{
_result = result;
Success = result.IsSuccess;
Data = result.Value;
Message = customMessage ?? result.ErrorMessage ?? (result.IsSuccess ? "Success" : "Failed");
ErrorCode = result.ErrorCode;
Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
}
/// <summary>
/// 是否成功
/// </summary>
public bool Success { get; }
/// <summary>
/// 响应数据
/// </summary>
public T? Data { get; }
/// <summary>
/// 消息
/// </summary>
public string Message { get; }
/// <summary>
/// 错误代码
/// </summary>
public long? ErrorCode { get; }
/// <summary>
/// 时间戳
/// </summary>
public long Timestamp { get; }
/// <summary>
/// 获取原始 Result
/// </summary>
public Result<T> ToResult() => _result;
}
@@ -0,0 +1,64 @@
using Microsoft.Extensions.DependencyInjection;
using Sharp.NetServer.Abstractions;
using Sharp.NetServer.Middleware;
namespace Sharp.NetServer.Extensions;
/// <summary>
/// 依赖注入扩展方法
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>
/// 添加 HTTP 服务器服务
/// </summary>
public static IServiceCollection AddHttpServer(this IServiceCollection services, Action<Server.HttpServerOptions>? configure = null)
{
var options = new Server.HttpServerOptions();
configure?.Invoke(options);
services.AddSingleton(options);
services.AddSingleton<Server.HttpServer>();
return services;
}
/// <summary>
/// 添加认证提供者
/// </summary>
public static IServiceCollection AddAuthentication<TProvider>(this IServiceCollection services)
where TProvider : class, IAuthenticationProvider
{
services.AddSingleton<IAuthenticationProvider, TProvider>();
return services;
}
/// <summary>
/// 添加 Token 提供者
/// </summary>
public static IServiceCollection AddTokenProvider<TProvider>(this IServiceCollection services)
where TProvider : class, ITokenProvider
{
services.AddSingleton<ITokenProvider, TProvider>();
return services;
}
/// <summary>
/// 添加响应缓存
/// </summary>
public static IServiceCollection AddResponseCache<TCache>(this IServiceCollection services)
where TCache : class, IResponseCache
{
services.AddSingleton<IResponseCache, TCache>();
return services;
}
/// <summary>
/// 添加内存响应缓存
/// </summary>
public static IServiceCollection AddInMemoryResponseCache(this IServiceCollection services)
{
services.AddSingleton<IResponseCache, InMemoryResponseCache>();
return services;
}
}
+144
View File
@@ -0,0 +1,144 @@
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Sharp.NetServer.Server;
namespace Sharp.NetServer;
/// <summary>
/// HTTP 服务器构建器 - 提供类似 ASP.NET Core 的 Fluent API
/// </summary>
public class HttpServerBuilder
{
private readonly HttpServerOptions _options;
private readonly ServiceCollection _services;
public HttpServerBuilder()
{
_options = new HttpServerOptions();
_services = new ServiceCollection();
// 注意:不再默认添加日志,由用户自己配置
// 用户可以通过 ConfigureServices 或 ConfigureLogging 添加日志
}
/// <summary>
/// 服务集合
/// </summary>
public IServiceCollection Services => _services;
/// <summary>
/// 配置监听地址
/// </summary>
public HttpServerBuilder UseUrls(params string[] urls)
{
_options.ListenUrls.Clear();
foreach (var url in urls)
{
_options.AddListenUrl(url);
}
return this;
}
/// <summary>
/// 添加控制器(从指定程序集)
/// </summary>
public HttpServerBuilder AddControllers(Assembly? assembly = null)
{
assembly ??= Assembly.GetEntryAssembly()!;
_options.AddControllerAssembly(assembly);
return this;
}
/// <summary>
/// 添加控制器(从指定类型所在的程序集)
/// </summary>
public HttpServerBuilder AddControllers<T>()
{
_options.AddControllerAssembly(typeof(T).Assembly);
return this;
}
/// <summary>
/// 启用 CORS
/// </summary>
public HttpServerBuilder UseCors(Action<Middleware.CorsOptions>? configure = null)
{
_options.UseCors = true;
configure?.Invoke(_options.CorsOptions);
return this;
}
/// <summary>
/// 启用认证
/// </summary>
public HttpServerBuilder UseAuthentication()
{
_options.UseAuthentication = true;
return this;
}
/// <summary>
/// 启用授权
/// </summary>
public HttpServerBuilder UseAuthorization()
{
_options.UseAuthorization = true;
return this;
}
/// <summary>
/// 启用限流
/// </summary>
public HttpServerBuilder UseRateLimit()
{
_options.UseRateLimit = true;
return this;
}
/// <summary>
/// 启用响应缓存
/// </summary>
public HttpServerBuilder UseResponseCache()
{
_options.UseResponseCache = true;
return this;
}
/// <summary>
/// 添加自定义中间件
/// </summary>
public HttpServerBuilder UseMiddleware(Func<Abstractions.RequestDelegate, Abstractions.RequestDelegate> middleware)
{
_options.AddMiddleware(middleware);
return this;
}
/// <summary>
/// 配置日志
/// 注意:需要用户自行添加日志实现包(如 Microsoft.Extensions.Logging.Console)
/// </summary>
public HttpServerBuilder ConfigureLogging(Action<IServiceCollection> configure)
{
configure(_services);
return this;
}
/// <summary>
/// 配置服务
/// </summary>
public HttpServerBuilder ConfigureServices(Action<IServiceCollection> configure)
{
configure(_services);
return this;
}
/// <summary>
/// 构建服务器
/// </summary>
public HttpServer Build()
{
var serviceProvider = _services.BuildServiceProvider();
return new HttpServer(_options, serviceProvider);
}
}
@@ -0,0 +1,145 @@
using System.Text;
using Sharp.NetServer.Abstractions;
using Sharp.NetServer.Models;
using Sharp.NetServer.Extensions;
namespace Sharp.NetServer.Middleware;
/// <summary>
/// 认证授权中间件
/// </summary>
public class AuthenticationMiddleware : IMiddleware
{
private readonly IAuthenticationProvider? _authProvider;
public AuthenticationMiddleware(IAuthenticationProvider? authProvider = null)
{
_authProvider = authProvider;
}
public async Task InvokeAsync(HttpContext context, Func<Task> next)
{
// 从请求头获取 Token
var token = ExtractToken(context);
// 如果有 Token,则验证身份
if (!string.IsNullOrEmpty(token) && _authProvider != null)
{
var principal = await _authProvider.AuthenticateAsync(token);
if (principal != null)
{
context.User = principal;
}
}
await next();
}
private static string? ExtractToken(HttpContext context)
{
// 从 Authorization 头获取 Bearer Token
var authHeader = context.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
return authHeader.Substring(7);
}
// 从 Cookie 获取 Token
var cookie = context.Request.Cookies["auth_token"];
if (cookie != null)
{
return cookie.Value;
}
// 从查询参数获取 Token
var queryToken = context.Request.QueryString["token"];
if (!string.IsNullOrEmpty(queryToken))
{
return queryToken;
}
return null;
}
}
/// <summary>
/// 授权检查中间件(配合路由系统使用)
/// </summary>
public class AuthorizationMiddleware : IMiddleware
{
public async Task InvokeAsync(HttpContext context, Func<Task> next)
{
// 检查是否需要授权(由路由系统设置)
if (context.Items.TryGetValue("RequireAuthorization", out var requireAuthObj) && requireAuthObj is bool requireAuth && requireAuth)
{
// 检查是否允许匿名访问
if (context.Items.TryGetValue("AllowAnonymous", out var allowAnonObj) && allowAnonObj is bool allowAnon && allowAnon)
{
await next();
return;
}
// 验证用户是否已认证
if (context.User?.Identity?.IsAuthenticated != true)
{
await WriteUnauthorizedResponseAsync(context, "Authentication required");
return;
}
// 验证角色
if (context.Items.TryGetValue("RequiredRoles", out var rolesObj) && rolesObj is string[] roles && roles.Length > 0)
{
var hasRole = roles.Any(role => context.User.IsInRole(role));
if (!hasRole)
{
await WriteForbiddenResponseAsync(context, "Insufficient permissions");
return;
}
}
// 验证权限(基于 Claims)
if (context.Items.TryGetValue("RequiredPermissions", out var permsObj) && permsObj is string[] permissions && permissions.Length > 0)
{
var userPermissions = context.User.Claims
.Where(c => c.Type == "permission")
.Select(c => c.Value)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
var hasPermission = permissions.Any(perm => userPermissions.Contains(perm));
if (!hasPermission)
{
await WriteForbiddenResponseAsync(context, "Insufficient permissions");
return;
}
}
}
await next();
}
private static async Task WriteUnauthorizedResponseAsync(HttpContext context, string message)
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json; charset=utf-8";
var response = ResultExtensions.HttpFailure<object>(message, 401);
var json = Common.Utils.JsonHelper.ToJson(response, useCompact: true);
var bytes = Encoding.UTF8.GetBytes(json);
context.Response.ContentLength = bytes.Length;
await context.Response.OutputStream.WriteAsync(bytes);
}
private static async Task WriteForbiddenResponseAsync(HttpContext context, string message)
{
context.Response.StatusCode = 403;
context.Response.ContentType = "application/json; charset=utf-8";
var response = ResultExtensions.HttpFailure<object>(message, 403);
var json = Common.Utils.JsonHelper.ToJson(response, useCompact: true);
var bytes = Encoding.UTF8.GetBytes(json);
context.Response.ContentLength = bytes.Length;
await context.Response.OutputStream.WriteAsync(bytes);
}
}
@@ -0,0 +1,92 @@
using System.Text;
using Sharp.NetServer.Abstractions;
using Sharp.NetServer.Models;
namespace Sharp.NetServer.Middleware;
/// <summary>
/// CORS 中间件
/// </summary>
public class CorsMiddleware : IMiddleware
{
private readonly CorsOptions _options;
public CorsMiddleware(CorsOptions? options = null)
{
_options = options ?? new CorsOptions();
}
public async Task InvokeAsync(HttpContext context, Func<Task> next)
{
var origin = context.Request.Headers["Origin"];
// 检查是否允许该来源
if (!string.IsNullOrEmpty(origin) && IsOriginAllowed(origin))
{
// 设置 CORS 响应头
context.Response.AddHeader("Access-Control-Allow-Origin",
_options.AllowAnyOrigin ? "*" : origin);
if (_options.AllowCredentials && !_options.AllowAnyOrigin)
{
context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
}
if (_options.AllowedHeaders.Length > 0)
{
context.Response.AddHeader("Access-Control-Allow-Headers",
string.Join(", ", _options.AllowedHeaders));
}
if (_options.AllowedMethods.Length > 0)
{
context.Response.AddHeader("Access-Control-Allow-Methods",
string.Join(", ", _options.AllowedMethods));
}
if (_options.ExposedHeaders.Length > 0)
{
context.Response.AddHeader("Access-Control-Expose-Headers",
string.Join(", ", _options.ExposedHeaders));
}
if (_options.MaxAge > 0)
{
context.Response.AddHeader("Access-Control-Max-Age",
_options.MaxAge.ToString());
}
}
// 处理预检请求
if (context.Request.HttpMethod.Equals("OPTIONS", StringComparison.OrdinalIgnoreCase))
{
context.Response.StatusCode = 204;
context.Response.ContentLength = 0;
return;
}
await next();
}
private bool IsOriginAllowed(string origin)
{
if (_options.AllowAnyOrigin)
return true;
return _options.AllowedOrigins.Contains(origin, StringComparer.OrdinalIgnoreCase);
}
}
/// <summary>
/// CORS 配置选项
/// </summary>
public class CorsOptions
{
public bool AllowAnyOrigin { get; set; } = true;
public string[] AllowedOrigins { get; set; } = Array.Empty<string>();
public string[] AllowedMethods { get; set; } = new[] { "GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH" };
public string[] AllowedHeaders { get; set; } = new[] { "Content-Type", "Authorization" };
public string[] ExposedHeaders { get; set; } = Array.Empty<string>();
public bool AllowCredentials { get; set; } = false;
public int MaxAge { get; set; } = 3600;
}
@@ -0,0 +1,58 @@
using System.Text;
using Microsoft.Extensions.Logging;
using Sharp.NetServer.Abstractions;
using Sharp.NetServer.Models;
using Sharp.NetServer.Extensions;
namespace Sharp.NetServer.Middleware;
/// <summary>
/// 全局异常处理中间件
/// </summary>
public class ExceptionHandlingMiddleware : IMiddleware
{
private readonly ILogger<ExceptionHandlingMiddleware>? _logger;
public ExceptionHandlingMiddleware(ILogger<ExceptionHandlingMiddleware>? logger = null)
{
_logger = logger;
}
public async Task InvokeAsync(HttpContext context, Func<Task> next)
{
try
{
await next();
}
catch (Exception ex)
{
_logger?.LogError(ex, "Unhandled exception occurred during request processing");
await HandleExceptionAsync(context, ex);
}
}
private static async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.StatusCode = 500;
context.Response.ContentType = "application/json; charset=utf-8";
#if DEBUG
// 仅在调试模式下返回详细错误信息
var debugInfo = new
{
exception.Message,
exception.StackTrace,
Type = exception.GetType().Name
};
var response = ResultExtensions.HttpSuccess(debugInfo, "An internal server error occurred");
#else
var response = ResultExtensions.HttpFailure<object>("An internal server error occurred", 500);
#endif
var json = Common.Utils.JsonHelper.ToJson(response, useCompact: true);
var bytes = Encoding.UTF8.GetBytes(json);
context.Response.ContentLength = bytes.Length;
await context.Response.OutputStream.WriteAsync(bytes);
}
}
@@ -0,0 +1,60 @@
using Microsoft.Extensions.Logging;
using Sharp.NetServer.Abstractions;
using Sharp.NetServer.Models;
namespace Sharp.NetServer.Middleware;
/// <summary>
/// 请求日志记录中间件
/// </summary>
public class LoggingMiddleware : IMiddleware
{
private readonly ILogger<LoggingMiddleware>? _logger;
public LoggingMiddleware(ILogger<LoggingMiddleware>? logger = null)
{
_logger = logger;
}
public async Task InvokeAsync(HttpContext context, Func<Task> next)
{
var startTime = DateTime.UtcNow;
var requestId = Guid.NewGuid().ToString("N")[..8];
_logger?.LogInformation(
"[{RequestId}] {Method} {Path} - Started from {ClientIp}",
requestId,
context.Request.HttpMethod,
context.Request.RawUrl,
context.Request.GetClientIp()
);
try
{
await next();
var duration = (DateTime.UtcNow - startTime).TotalMilliseconds;
_logger?.LogInformation(
"[{RequestId}] {Method} {Path} - Completed with {StatusCode} in {Duration}ms",
requestId,
context.Request.HttpMethod,
context.Request.RawUrl,
context.Response.StatusCode,
duration
);
}
catch (Exception ex)
{
var duration = (DateTime.UtcNow - startTime).TotalMilliseconds;
_logger?.LogError(
ex,
"[{RequestId}] {Method} {Path} - Failed in {Duration}ms",
requestId,
context.Request.HttpMethod,
context.Request.RawUrl,
duration
);
throw;
}
}
}
@@ -0,0 +1,67 @@
using Sharp.NetServer.Abstractions;
using Sharp.NetServer.Models;
namespace Sharp.NetServer.Middleware;
/// <summary>
/// 中间件管道 - 管理和执行中间件链
/// </summary>
public class MiddlewarePipeline
{
private readonly List<Func<RequestDelegate, RequestDelegate>> _middlewares = new();
private RequestDelegate? _pipeline;
/// <summary>
/// 添加中间件
/// </summary>
public void Use(Func<RequestDelegate, RequestDelegate> middleware)
{
_middlewares.Add(middleware);
_pipeline = null; // 重置管道,下次调用时重新构建
}
/// <summary>
/// 添加中间件(基于 IMiddleware 接口)
/// </summary>
public void Use<T>() where T : IMiddleware, new()
{
Use(next =>
{
var middleware = new T();
return async context => await middleware.InvokeAsync(context, async () => await next(context));
});
}
/// <summary>
/// 添加中间件(通过工厂方法)
/// </summary>
public void Use(Func<HttpContext, Func<Task>, Task> middleware)
{
Use(next =>
{
return async context => await middleware(context, async () => await next(context));
});
}
/// <summary>
/// 执行中间件管道
/// </summary>
public async Task ExecuteAsync(HttpContext context)
{
_pipeline ??= BuildPipeline();
await _pipeline(context);
}
private RequestDelegate BuildPipeline()
{
RequestDelegate pipeline = context => Task.CompletedTask;
// 逆序构建管道
for (int i = _middlewares.Count - 1; i >= 0; i--)
{
pipeline = _middlewares[i](pipeline);
}
return pipeline;
}
}
@@ -0,0 +1,169 @@
using System.Collections.Concurrent;
using System.Text;
using Sharp.NetServer.Abstractions;
using Sharp.NetServer.Models;
using Sharp.NetServer.Extensions;
namespace Sharp.NetServer.Middleware;
/// <summary>
/// 限流中间件
/// </summary>
public class RateLimitMiddleware : IMiddleware
{
private readonly ConcurrentDictionary<string, RateLimitCounter> _counters = new();
public async Task InvokeAsync(HttpContext context, Func<Task> next)
{
// 检查是否有限流配置
if (!context.Items.TryGetValue("RateLimitConfig", out var configObj) || configObj is not Routing.RateLimitConfig config)
{
await next();
return;
}
// 生成限流键
var key = GenerateRateLimitKey(context, config.Scope);
// 获取或创建计数器
var counter = _counters.GetOrAdd(key, _ => new RateLimitCounter(config.WindowSeconds));
// 清理过期的计数器(定期清理,避免内存泄漏)
CleanupExpiredCounters();
// 检查是否超过限流阈值
if (!counter.TryIncrement(config.MaxRequests))
{
await WriteRateLimitExceededResponseAsync(context, counter.GetRetryAfter());
return;
}
// 添加限流响应头
context.Response.AddHeader("X-RateLimit-Limit", config.MaxRequests.ToString());
context.Response.AddHeader("X-RateLimit-Remaining", counter.GetRemaining(config.MaxRequests).ToString());
context.Response.AddHeader("X-RateLimit-Reset", counter.GetResetTime().ToString());
await next();
}
private static string GenerateRateLimitKey(HttpContext context, string scope)
{
var endpoint = context.Request.RawUrl;
return scope.ToLower() switch
{
"global" => "global",
"ip" => $"ip:{context.Request.GetClientIp()}",
"user" => $"user:{context.User?.Identity?.Name ?? "anonymous"}",
"endpoint" => $"endpoint:{endpoint}",
_ => $"ip:{context.Request.GetClientIp()}:endpoint:{endpoint}"
};
}
private void CleanupExpiredCounters()
{
// 每 100 次请求清理一次过期计数器
if (Random.Shared.Next(100) == 0)
{
var expiredKeys = _counters
.Where(kvp => kvp.Value.IsExpired())
.Select(kvp => kvp.Key)
.ToList();
foreach (var key in expiredKeys)
{
_counters.TryRemove(key, out _);
}
}
}
private static async Task WriteRateLimitExceededResponseAsync(HttpContext context, int retryAfter)
{
context.Response.StatusCode = 429;
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.AddHeader("Retry-After", retryAfter.ToString());
var response = ResultExtensions.HttpFailure<object>("Too many requests. Please try again later.", 429);
var json = Common.Utils.JsonHelper.ToJson(response, useCompact: true);
var bytes = Encoding.UTF8.GetBytes(json);
context.Response.ContentLength = bytes.Length;
await context.Response.OutputStream.WriteAsync(bytes);
}
}
/// <summary>
/// 限流计数器
/// </summary>
internal class RateLimitCounter
{
private readonly int _windowSeconds;
private readonly object _lock = new();
private DateTime _windowStart;
private int _count;
public RateLimitCounter(int windowSeconds)
{
_windowSeconds = windowSeconds;
_windowStart = DateTime.UtcNow;
_count = 0;
}
public bool TryIncrement(int maxRequests)
{
lock (_lock)
{
var now = DateTime.UtcNow;
// 检查时间窗口是否过期
if ((now - _windowStart).TotalSeconds >= _windowSeconds)
{
_windowStart = now;
_count = 0;
}
// 检查是否超过限制
if (_count >= maxRequests)
{
return false;
}
_count++;
return true;
}
}
public int GetRemaining(int maxRequests)
{
lock (_lock)
{
return Math.Max(0, maxRequests - _count);
}
}
public long GetResetTime()
{
lock (_lock)
{
var resetTime = _windowStart.AddSeconds(_windowSeconds);
return new DateTimeOffset(resetTime).ToUnixTimeSeconds();
}
}
public int GetRetryAfter()
{
lock (_lock)
{
var resetTime = _windowStart.AddSeconds(_windowSeconds);
return (int)Math.Ceiling((resetTime - DateTime.UtcNow).TotalSeconds);
}
}
public bool IsExpired()
{
lock (_lock)
{
return (DateTime.UtcNow - _windowStart).TotalSeconds >= _windowSeconds * 2;
}
}
}
@@ -0,0 +1,189 @@
using System.Collections.Concurrent;
using System.Text;
using Sharp.NetServer.Abstractions;
using Sharp.NetServer.Models;
namespace Sharp.NetServer.Middleware;
/// <summary>
/// 响应缓存中间件
/// </summary>
public class ResponseCacheMiddleware : IMiddleware
{
private readonly IResponseCache _cache;
public ResponseCacheMiddleware(IResponseCache? cache = null)
{
_cache = cache ?? new InMemoryResponseCache();
}
public async Task InvokeAsync(HttpContext context, Func<Task> next)
{
// 检查是否有缓存配置
if (!context.Items.TryGetValue("CacheConfig", out var configObj) || configObj is not Routing.CacheConfig config)
{
await next();
return;
}
// 只缓存 GET 请求
if (!context.Request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase))
{
await next();
return;
}
// 生成缓存键
var cacheKey = GenerateCacheKey(context, config);
// 尝试从缓存获取
var cachedResponse = await _cache.GetAsync(cacheKey);
if (cachedResponse != null)
{
await WriteCachedResponseAsync(context, cachedResponse);
return;
}
// 捕获响应
var originalStream = context.Response.OutputStream;
using var memoryStream = new MemoryStream();
// 临时替换输出流
var response = context.Response;
var originalContentType = response.ContentType;
var originalStatusCode = response.StatusCode;
// 执行下一个中间件
await next();
// 如果响应成功,缓存结果
if (response.StatusCode == 200)
{
// 注意:由于 HttpListenerResponse 的限制,我们无法直接拦截输出流
// 这里提供一个简化的实现,实际使用中可能需要在控制器层面配合
var cachedData = new CachedResponse
{
ContentType = response.ContentType ?? "application/json",
StatusCode = response.StatusCode,
Headers = new Dictionary<string, string>(),
// Body 需要在控制器中通过特殊处理来缓存
};
await _cache.SetAsync(cacheKey, cachedData, TimeSpan.FromSeconds(config.Duration));
}
}
private static string GenerateCacheKey(HttpContext context, Routing.CacheConfig config)
{
var path = context.Request.RawUrl;
// 如果指定了自定义缓存键
if (!string.IsNullOrEmpty(config.CacheKey))
{
// TODO: 支持占位符替换,如 {userId}
return config.CacheKey;
}
// 默认使用路径作为键
var key = $"cache:{path}";
// 如果需要根据查询参数变化
if (config.VaryByQueryKeys && context.Request.QueryString.Count > 0)
{
var queryParams = string.Join("&",
context.Request.QueryString.AllKeys
.OrderBy(k => k)
.Select(k => $"{k}={context.Request.QueryString[k]}"));
key += $"?{queryParams}";
}
return key;
}
private static async Task WriteCachedResponseAsync(HttpContext context, CachedResponse cachedResponse)
{
context.Response.StatusCode = cachedResponse.StatusCode;
context.Response.ContentType = cachedResponse.ContentType;
context.Response.AddHeader("X-Cache", "HIT");
foreach (var header in cachedResponse.Headers)
{
context.Response.AddHeader(header.Key, header.Value);
}
if (cachedResponse.Body != null)
{
context.Response.ContentLength = cachedResponse.Body.Length;
await context.Response.OutputStream.WriteAsync(cachedResponse.Body);
}
}
}
/// <summary>
/// 响应缓存接口
/// </summary>
public interface IResponseCache
{
Task<CachedResponse?> GetAsync(string key);
Task SetAsync(string key, CachedResponse value, TimeSpan expiration);
Task RemoveAsync(string key);
}
/// <summary>
/// 缓存的响应数据
/// </summary>
public class CachedResponse
{
public string ContentType { get; set; } = string.Empty;
public int StatusCode { get; set; }
public Dictionary<string, string> Headers { get; set; } = new();
public byte[]? Body { get; set; }
}
/// <summary>
/// 内存响应缓存实现
/// </summary>
public class InMemoryResponseCache : IResponseCache
{
private readonly ConcurrentDictionary<string, CacheEntry> _cache = new();
public Task<CachedResponse?> GetAsync(string key)
{
if (_cache.TryGetValue(key, out var entry))
{
if (entry.ExpiresAt > DateTime.UtcNow)
{
return Task.FromResult<CachedResponse?>(entry.Response);
}
// 过期,移除
_cache.TryRemove(key, out _);
}
return Task.FromResult<CachedResponse?>(null);
}
public Task SetAsync(string key, CachedResponse value, TimeSpan expiration)
{
var entry = new CacheEntry
{
Response = value,
ExpiresAt = DateTime.UtcNow.Add(expiration)
};
_cache[key] = entry;
return Task.CompletedTask;
}
public Task RemoveAsync(string key)
{
_cache.TryRemove(key, out _);
return Task.CompletedTask;
}
private class CacheEntry
{
public CachedResponse Response { get; set; } = null!;
public DateTime ExpiresAt { get; set; }
}
}
+146
View File
@@ -0,0 +1,146 @@
using System.Collections.Specialized;
using System.Net;
using System.Security.Claims;
namespace Sharp.NetServer.Models;
/// <summary>
/// HTTP 上下文封装
/// </summary>
public class HttpContext
{
private readonly HttpListenerContext _context;
private Dictionary<string, object>? _items;
public HttpContext(HttpListenerContext context)
{
_context = context;
Request = new HttpRequestWrapper(context.Request);
Response = new HttpResponseWrapper(context.Response);
}
/// <summary>
/// 请求对象
/// </summary>
public HttpRequestWrapper Request { get; }
/// <summary>
/// 响应对象
/// </summary>
public HttpResponseWrapper Response { get; }
/// <summary>
/// 用户身份信息
/// </summary>
public ClaimsPrincipal? User { get; set; }
/// <summary>
/// 上下文数据存储(用于中间件间传递数据)
/// </summary>
public Dictionary<string, object> Items => _items ??= new Dictionary<string, object>();
/// <summary>
/// 取消令牌
/// </summary>
public CancellationToken CancellationToken { get; set; }
}
/// <summary>
/// HTTP 请求包装器
/// </summary>
public class HttpRequestWrapper
{
private readonly HttpListenerRequest _request;
public HttpRequestWrapper(HttpListenerRequest request)
{
_request = request;
}
public string HttpMethod => _request.HttpMethod;
public Uri Url => _request.Url!;
public string RawUrl => _request.RawUrl ?? string.Empty;
public NameValueCollection Headers => _request.Headers;
public NameValueCollection QueryString => _request.QueryString;
public string? ContentType => _request.ContentType;
public long ContentLength => _request.ContentLength64;
public Stream InputStream => _request.InputStream;
public bool HasEntityBody => _request.HasEntityBody;
public IPEndPoint RemoteEndPoint => _request.RemoteEndPoint;
public string UserAgent => _request.UserAgent ?? string.Empty;
public CookieCollection Cookies => _request.Cookies;
/// <summary>
/// 获取客户端 IP 地址
/// </summary>
public string GetClientIp()
{
// 优先从 X-Forwarded-For 获取(适用于代理/负载均衡场景)
var forwardedFor = Headers["X-Forwarded-For"];
if (!string.IsNullOrEmpty(forwardedFor))
{
var ips = forwardedFor.Split(',');
return ips[0].Trim();
}
// 从 X-Real-IP 获取
var realIp = Headers["X-Real-IP"];
if (!string.IsNullOrEmpty(realIp))
{
return realIp.Trim();
}
// 直接从远程端点获取
return RemoteEndPoint.Address.ToString();
}
}
/// <summary>
/// HTTP 响应包装器
/// </summary>
public class HttpResponseWrapper
{
private readonly HttpListenerResponse _response;
public HttpResponseWrapper(HttpListenerResponse response)
{
_response = response;
}
public int StatusCode
{
get => _response.StatusCode;
set => _response.StatusCode = value;
}
public string? ContentType
{
get => _response.ContentType;
set => _response.ContentType = value;
}
public long ContentLength
{
get => _response.ContentLength64;
set => _response.ContentLength64 = value;
}
public Stream OutputStream => _response.OutputStream;
public WebHeaderCollection Headers => _response.Headers;
public CookieCollection Cookies => _response.Cookies;
public void AddHeader(string name, string value)
{
_response.AddHeader(name, value);
}
public void Redirect(string url)
{
_response.Redirect(url);
}
public void Close()
{
_response.Close();
}
}
+12
View File
@@ -4,6 +4,18 @@
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>Sharp.NetServer</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Common\Common.csproj" />
<ProjectReference Include="..\Config\Config.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.0" />
</ItemGroup>
</Project>
+349
View File
@@ -0,0 +1,349 @@
# Sharp.NetServer
基于 HttpListener 的轻量级 Web 框架,提供类似 Spring Boot 的开发体验。
## 特性
- ✅ **特性路由** - 使用 `[Route]`、`[HttpGet]` 等特性定义路由
- ✅ **认证授权** - 支持 `[Authorize]`、`[AllowAnonymous]` 特性
- ✅ **限流** - 通过 `[RateLimit]` 特性控制请求频率
- ✅ **响应缓存** - 使用 `[ResponseCache]` 缓存响应
- ✅ **CORS 支持** - 配置跨域资源共享
- ✅ **中间件管道** - 灵活的中间件系统
- ✅ **全局异常处理** - 统一错误处理
- ✅ **日志记录** - 集成 Microsoft.Extensions.Logging
- ✅ **依赖注入** - 集成 Microsoft.Extensions.DependencyInjection
## 快速开始
### 1. 安装依赖
在项目中引用 `Sharp.NetServer` 项目或 NuGet 包。
### 2. 创建控制器
```csharp
using Sharp.NetServer.Attributes;
using Sharp.NetServer.Controllers;
using Sharp.NetServer.Models;
[ApiController]
[Route("greet")]
[Authorize] // 类级别默认要求认证
public class GreetController : BaseController
{
/// <summary>
/// 问候接口:允许匿名访问,并限制每个 IP 每分钟 120 次
/// GET /greet/hello?name=Tom
/// </summary>
[AllowAnonymous]
[RateLimit(120, RateLimitScope.Ip)]
[HttpGet("hello")]
public async Task HelloAsync(HttpContext context)
{
var name = GetQueryParam(context, "name", "世界");
await WriteSuccessResponseAsync(context, new { greeting = $"你好, {name}!" });
}
/// <summary>
/// 需要认证的接口
/// GET /greet/user
/// </summary>
[HttpGet("user")]
public async Task GetUserAsync(HttpContext context)
{
var userName = context.User?.Identity?.Name ?? "未知";
await WriteSuccessResponseAsync(context, new { userName });
}
}
```
### 3. 配置和启动服务器
#### 方式一:使用 HttpServerBuilder(推荐)
```csharp
using Sharp.NetServer;
var builder = new HttpServerBuilder();
// 配置监听地址
builder.UseUrls("http://localhost:5000/", "http://localhost:5001/");
// 添加控制器
builder.AddControllers(); // 从入口程序集添加
// 启用功能
builder.UseCors(options =>
{
options.AllowAnyOrigin = true;
options.AllowedMethods = new[] { "GET", "POST", "PUT", "DELETE" };
});
builder.UseAuthentication();
builder.UseAuthorization();
builder.UseRateLimit();
builder.UseResponseCache();
// 配置日志
builder.ConfigureLogging(logging =>
{
logging.AddConsole();
logging.SetMinimumLevel(LogLevel.Information);
});
// 添加认证提供者(可选)
builder.ConfigureServices(services =>
{
services.AddAuthentication<MyAuthProvider>();
});
// 构建并启动
var server = builder.Build();
await server.StartAsync();
Console.WriteLine("Press any key to stop...");
Console.ReadKey();
server.Stop();
```
#### 方式二:使用 HttpServer 和 HttpServerOptions
```csharp
using Sharp.NetServer.Server;
using System.Reflection;
var options = new HttpServerOptions
{
ListenUrls = new() { "http://localhost:5000/" },
UseAuthentication = true,
UseAuthorization = true,
UseRateLimit = true,
UseResponseCache = true
};
options.AddControllerAssembly(Assembly.GetExecutingAssembly());
var server = new HttpServer(options);
await server.StartAsync();
```
## 核心概念
### 特性(Attributes)
#### 路由特性
```csharp
[Route("api/users")] // 类级别路由前缀
[HttpGet("list")] // GET /api/users/list
[HttpPost("create")] // POST /api/users/create
[HttpPut("update/{id}")] // PUT /api/users/update/123
[HttpDelete("delete/{id}")] // DELETE /api/users/delete/123
```
#### 认证授权
```csharp
[Authorize] // 需要认证
[Authorize(Roles = "Admin,Manager")] // 需要角色
[Authorize(Permissions = "users.read")] // 需要权限
[AllowAnonymous] // 允许匿名访问
```
#### 限流
```csharp
[RateLimit(100, RateLimitScope.Ip)] // 每个 IP 每分钟 100 次
[RateLimit(50, RateLimitScope.User)] // 每个用户每分钟 50 次
[RateLimit(1000, RateLimitScope.Global)] // 全局每分钟 1000 次
[RateLimit(200, RateLimitScope.Endpoint)] // 每个端点每分钟 200 次
```
#### 缓存
```csharp
[ResponseCache(60)] // 缓存 60 秒
[ResponseCache(300, VaryByQueryKeys = true)] // 根据查询参数缓存
```
#### CORS
```csharp
[EnableCors(Origins = "http://localhost:3000", AllowCredentials = true)]
[DisableCors]
```
### 控制器基类
`BaseController` 提供了丰富的辅助方法:
```csharp
// 读取请求
var query = GetQueryParam(context, "name", "default");
var header = GetHeader(context, "Authorization");
var body = await ReadRequestBodyAsync(context);
var data = await ReadJsonBodyAsync<MyModel>(context);
// 写入响应
await WriteJsonResponseAsync(context, data);
await WriteSuccessResponseAsync(context, data, "Success");
await WriteErrorResponseAsync(context, "Error message", 500);
await WriteTextResponseAsync(context, "Plain text");
await WriteHtmlResponseAsync(context, "<h1>HTML</h1>");
// 快速响应
await NotFoundAsync(context);
await UnauthorizedAsync(context);
await ForbiddenAsync(context);
await BadRequestAsync(context);
Redirect(context, "/new-url");
// Cookie 操作
SetCookie(context, "name", "value", expiresInSeconds: 3600);
var value = GetCookie(context, "name");
DeleteCookie(context, "name");
```
### 中间件
#### 内置中间件
框架内置以下中间件(按执行顺序):
1. **ExceptionHandlingMiddleware** - 全局异常处理
2. **LoggingMiddleware** - 请求日志记录
3. **CorsMiddleware** - CORS 处理
4. **AuthenticationMiddleware** - 身份认证
5. **AuthorizationMiddleware** - 授权检查
6. **RateLimitMiddleware** - 限流
7. **ResponseCacheMiddleware** - 响应缓存
8. **RouteHandler** - 路由处理
#### 自定义中间件
```csharp
builder.UseMiddleware(next => async context =>
{
Console.WriteLine($"Request: {context.Request.RawUrl}");
await next(context);
Console.WriteLine($"Response: {context.Response.StatusCode}");
});
```
### 认证
实现 `IAuthenticationProvider` 接口:
```csharp
using Sharp.NetServer.Abstractions;
using System.Security.Claims;
public class JwtAuthProvider : IAuthenticationProvider
{
public async Task<ClaimsPrincipal?> AuthenticateAsync(string? token)
{
if (string.IsNullOrEmpty(token))
return null;
// 验证 JWT Token
var claims = ValidateJwtToken(token);
if (claims == null)
return null;
var identity = new ClaimsIdentity(claims, "Bearer");
return new ClaimsPrincipal(identity);
}
private List<Claim>? ValidateJwtToken(string token)
{
// 实现 JWT 验证逻辑
return new List<Claim>
{
new Claim(ClaimTypes.Name, "user123"),
new Claim(ClaimTypes.Role, "Admin"),
new Claim("permission", "users.read")
};
}
}
// 注册
builder.ConfigureServices(services =>
{
services.AddAuthentication<JwtAuthProvider>();
});
```
## 高级功能
### 依赖注入
```csharp
// 注册服务
builder.ConfigureServices(services =>
{
services.AddSingleton<IMyService, MyService>();
services.AddScoped<IUserRepository, UserRepository>();
});
// 在控制器中使用(需要通过构造函数注入)
public class UserController : BaseController
{
private readonly IUserRepository _repository;
public UserController(IUserRepository repository)
{
_repository = repository;
}
}
```
### 响应模型
框架提供了标准的响应模型 `ResponseModel<T>`:
```csharp
{
"success": true,
"data": { ... },
"message": "Success",
"errorCode": null,
"timestamp": 1234567890
}
```
### 日志记录
使用 Microsoft.Extensions.Logging:
```csharp
builder.ConfigureLogging(logging =>
{
logging.AddConsole();
logging.AddDebug();
logging.SetMinimumLevel(LogLevel.Information);
});
```
## 示例项目
参考 `Examples/DemoController.cs` 查看完整示例。
## 性能建议
1. **启用限流** - 防止滥用和 DDoS 攻击
2. **使用缓存** - 对于不经常变化的数据启用响应缓存
3. **异步方法** - 所有控制器方法使用 `async/await`
4. **日志级别** - 生产环境设置为 `Information` 或 `Warning`
5. **CORS 配置** - 生产环境不要使用 `AllowAnyOrigin = true`
## 注意事项
1. **管理员权限** - Windows 上监听非 localhost 地址需要管理员权限
2. **HTTPS** - HttpListener 支持 HTTPS,需要配置 SSL 证书
3. **并发** - 框架内置并发处理,无需额外配置
4. **线程安全** - 中间件和控制器需要保证线程安全
## 许可证
MIT License
+227
View File
@@ -0,0 +1,227 @@
# NetServer 重构建议
## 🎯 重构目标
1. **删除 ResponseModel**,改用 Common 的 Result
2. **减少依赖**,移除不必要的包引用
3. **统一标准**,所有模块使用相同的结果类型
## 📋 重构步骤
### 第一步:替换 ResponseModel 为 HttpResult
#### 1.1 修改 BaseController
**修改前:**
```csharp
protected async Task WriteSuccessResponseAsync<T>(HttpContext context, T data, string? message = null)
{
var response = ResponseModel<T>.Ok(data, message);
await WriteJsonResponseAsync(context, response);
}
```
**修改后:**
```csharp
protected async Task WriteSuccessResponseAsync<T>(HttpContext context, T data, string? message = null)
{
var response = ResultExtensions.HttpSuccess(data, message);
await WriteJsonResponseAsync(context, response);
}
```
#### 1.2 修改所有中间件
在所有中间件中,将 `ResponseModel<object>` 替换为 `HttpResult<object>`。
### 第二步:优化依赖
#### 2.1 保留的依赖(合理且必要)
```xml
<ItemGroup>
<ProjectReference Include="..\Common\Common.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.0" />
</ItemGroup>
```
#### 2.2 可移除的依赖
```xml
<!-- 这些可以移除,因为不是所有用户都需要控制台日志 -->
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
```
> **注意**:日志的具体实现(如 Console)应该由使用者决定,框架只依赖抽象即可。
### 第三步:删除重复文件
```bash
# 删除 ResponseModel.cs
rm src/Sharp/NetServer/Models/ResponseModel.cs
```
## 🔄 迁移指南
### 对于框架使用者
**修改前:**
```csharp
var response = ResponseModel<User>.Ok(user, "查询成功");
await WriteJsonResponseAsync(context, response);
```
**修改后:**
```csharp
var response = ResultExtensions.HttpSuccess(user, "查询成功");
await WriteJsonResponseAsync(context, response);
// 或者使用 Result
var result = Result.Success(user);
var httpResult = result.ToHttpResult();
await WriteJsonResponseAsync(context, httpResult);
```
### API 响应格式保持不变
```json
{
"success": true,
"data": { "id": 1, "name": "张三" },
"message": "Success",
"errorCode": null,
"timestamp": 1734567890123
}
```
## 📊 对比分析
### 重构前
```
NetServer
├── Models/
│ ├── HttpContext.cs
│ └── ResponseModel.cs ❌ 重复
├── 依赖:
│ ├── Common ✅
│ ├── Microsoft.Extensions.Logging ⚠️ 过度依赖
│ └── Microsoft.Extensions.Logging.Console ⚠️ 过度依赖
```
### 重构后
```
NetServer
├── Models/
│ └── HttpContext.cs
├── Extensions/
│ └── ResultExtensions.cs ✅ 基于 Common.Result
├── 依赖:
│ ├── Common ✅
│ └── Microsoft.Extensions.*.Abstractions ✅ 仅抽象
```
## ✅ 重构优点
1. **避免重复** - 使用 Common 的 Result,删除 ResponseModel
2. **功能更强** - Result 提供了更多功能(Map、Bind、Try 等)
3. **统一标准** - 所有模块使用相同的结果类型
4. **减少依赖** - 移除具体实现的依赖,只保留抽象
5. **更灵活** - 用户可以选择自己的日志实现
## 🚀 实施建议
### 立即执行(重要)
1. ✅ 创建 ResultExtensions.cs(已完成)
2. 🔄 修改 BaseController 使用 HttpResult
3. 🔄 修改所有中间件使用 HttpResult
4. ❌ 删除 ResponseModel.cs
5. 🔄 更新项目依赖
### 后续优化(可选)
1. 考虑是否需要 Common 依赖
- 如果保留:充分利用 Common 的功能
- 如果移除:复制必要的代码到 NetServer
2. 提供适配器模式
- 允许用户自定义响应格式
- 提供接口让用户实现自己的 IHttpResult
## 💡 架构建议
### 关于依赖的原则
**NetServer 作为公共模块应该:**
1. ✅ **依赖抽象而不是实现**
- 依赖 `Microsoft.Extensions.Logging.Abstractions` ✅
- 不依赖 `Microsoft.Extensions.Logging.Console` ❌
2. ✅ **依赖稳定的基础库**
- Common(项目内基础库)✅
- Microsoft.Extensions.*(.NET 标准库)✅
3. ❌ **避免依赖具体实现**
- 日志具体实现(Console、File)❌
- 缓存具体实现(Redis、Memory)❌
- 数据库实现(EF Core、Dapper)❌
### 推荐的依赖结构
```
NetServer(核心)
├── Common(基础工具)✅
├── Microsoft.Extensions.*.Abstractions(抽象)✅
└── 用户提供的实现(通过 DI)✅
NetServer.Extensions(可选扩展包)
├── NetServer ✅
├── Microsoft.Extensions.Logging.Console ✅
├── StackExchange.Redis ✅
└── 其他具体实现 ✅
```
## 🎯 最终建议
### 方案选择
**推荐方案:充分利用 Common,删除重复代码**
理由:
1. Common 是项目的基础库,设计目的就是被其他模块使用
2. Result 类设计完善,功能强大
3. 统一标准,避免维护两套相似的代码
4. 用户引用 NetServer 时可以同时享受 Common 的便利
### 实施优先级
1. **高优先级**(必须执行)
- 使用 HttpResult 替换 ResponseModel
- 移除 `Microsoft.Extensions.Logging.Console` 依赖
2. **中优先级**(建议执行)
- 检查是否还有其他重复功能
- 完善 ResultExtensions 的文档
3. **低优先级**(可以延后)
- 考虑创建 NetServer.Extensions 扩展包
- 提供更多的适配器和转换器
## 📝 总结
通过这次重构,NetServer 将:
- ✅ 更轻量(减少不必要的依赖)
- ✅ 更统一(使用 Common 的标准)
- ✅ 更灵活(用户可以自由选择实现)
- ✅ 更易维护(避免重复代码)
这完全符合"NetServer 作为公共模块"的定位!
+97
View File
@@ -0,0 +1,97 @@
using System.Reflection;
namespace Sharp.NetServer.Routing;
/// <summary>
/// 路由信息
/// </summary>
public class RouteInfo
{
/// <summary>
/// HTTP 方法
/// </summary>
public string HttpMethod { get; set; } = string.Empty;
/// <summary>
/// 路由模板
/// </summary>
public string Template { get; set; } = string.Empty;
/// <summary>
/// 控制器类型
/// </summary>
public Type ControllerType { get; set; } = null!;
/// <summary>
/// 处理方法
/// </summary>
public MethodInfo Method { get; set; } = null!;
/// <summary>
/// 是否需要授权
/// </summary>
public bool RequireAuthorization { get; set; }
/// <summary>
/// 允许匿名访问
/// </summary>
public bool AllowAnonymous { get; set; }
/// <summary>
/// 所需角色
/// </summary>
public string[]? Roles { get; set; }
/// <summary>
/// 所需权限
/// </summary>
public string[]? Permissions { get; set; }
/// <summary>
/// 限流配置
/// </summary>
public RateLimitConfig? RateLimitConfig { get; set; }
/// <summary>
/// 缓存配置
/// </summary>
public CacheConfig? CacheConfig { get; set; }
/// <summary>
/// CORS 配置
/// </summary>
public CorsConfig? CorsConfig { get; set; }
}
/// <summary>
/// 限流配置
/// </summary>
public class RateLimitConfig
{
public int MaxRequests { get; set; }
public int WindowSeconds { get; set; }
public string Scope { get; set; } = string.Empty;
}
/// <summary>
/// 缓存配置
/// </summary>
public class CacheConfig
{
public int Duration { get; set; }
public string Strategy { get; set; } = string.Empty;
public bool VaryByQueryKeys { get; set; }
public string? CacheKey { get; set; }
}
/// <summary>
/// CORS 配置
/// </summary>
public class CorsConfig
{
public string[] Origins { get; set; } = Array.Empty<string>();
public string[] Methods { get; set; } = Array.Empty<string>();
public string[] Headers { get; set; } = Array.Empty<string>();
public bool AllowCredentials { get; set; }
public int MaxAge { get; set; }
}
+157
View File
@@ -0,0 +1,157 @@
using System.Reflection;
using System.Text.RegularExpressions;
using Sharp.NetServer.Attributes;
namespace Sharp.NetServer.Routing;
/// <summary>
/// 路由表 - 管理所有路由信息
/// </summary>
public class RouteTable
{
private readonly List<RouteInfo> _routes = new();
/// <summary>
/// 注册控制器
/// </summary>
public void RegisterController(Type controllerType)
{
if (!controllerType.IsClass || controllerType.IsAbstract)
return;
var controllerRoute = controllerType.GetCustomAttribute<RouteAttribute>();
var controllerAuthorize = controllerType.GetCustomAttribute<AuthorizeAttribute>();
var controllerCors = controllerType.GetCustomAttribute<EnableCorsAttribute>();
var controllerRateLimit = controllerType.GetCustomAttribute<RateLimitAttribute>();
var methods = controllerType.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Where(m => m.GetCustomAttribute<HttpMethodAttribute>() != null);
foreach (var method in methods)
{
var httpMethodAttr = method.GetCustomAttribute<HttpMethodAttribute>()!;
var methodRoute = method.GetCustomAttribute<RouteAttribute>();
var methodAuthorize = method.GetCustomAttribute<AuthorizeAttribute>();
var methodAllowAnonymous = method.GetCustomAttribute<AllowAnonymousAttribute>();
var methodRateLimit = method.GetCustomAttribute<RateLimitAttribute>();
var methodCache = method.GetCustomAttribute<ResponseCacheAttribute>();
var methodCors = method.GetCustomAttribute<EnableCorsAttribute>();
var disableCors = method.GetCustomAttribute<DisableCorsAttribute>();
// 构建完整路由
var routeTemplate = BuildRouteTemplate(
controllerRoute?.Template,
methodRoute?.Template ?? httpMethodAttr.Template
);
// 确定授权需求
var authorize = methodAuthorize ?? controllerAuthorize;
var requireAuth = authorize != null && methodAllowAnonymous == null;
var routeInfo = new RouteInfo
{
HttpMethod = httpMethodAttr.Method,
Template = routeTemplate,
ControllerType = controllerType,
Method = method,
RequireAuthorization = requireAuth,
AllowAnonymous = methodAllowAnonymous != null,
Roles = authorize?.Roles?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries),
Permissions = authorize?.Permissions?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries),
};
// 限流配置
var rateLimit = methodRateLimit ?? controllerRateLimit;
if (rateLimit != null)
{
routeInfo.RateLimitConfig = new RateLimitConfig
{
MaxRequests = rateLimit.MaxRequests,
WindowSeconds = rateLimit.WindowSeconds,
Scope = rateLimit.Scope.ToString()
};
}
// 缓存配置
if (methodCache != null)
{
routeInfo.CacheConfig = new CacheConfig
{
Duration = methodCache.Duration,
Strategy = methodCache.Strategy.ToString(),
VaryByQueryKeys = methodCache.VaryByQueryKeys,
CacheKey = methodCache.CacheKey
};
}
// CORS 配置
if (disableCors == null)
{
var cors = methodCors ?? controllerCors;
if (cors != null)
{
routeInfo.CorsConfig = new CorsConfig
{
Origins = cors.Origins.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries),
Methods = cors.Methods.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries),
Headers = cors.Headers.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries),
AllowCredentials = cors.AllowCredentials,
MaxAge = cors.MaxAge
};
}
}
_routes.Add(routeInfo);
}
}
/// <summary>
/// 查找匹配的路由
/// </summary>
public RouteInfo? FindRoute(string httpMethod, string path)
{
foreach (var route in _routes)
{
if (route.HttpMethod != httpMethod.ToUpper())
continue;
if (IsRouteMatch(route.Template, path))
return route;
}
return null;
}
/// <summary>
/// 获取所有路由
/// </summary>
public IReadOnlyList<RouteInfo> GetAllRoutes() => _routes.AsReadOnly();
private static string BuildRouteTemplate(string? controllerRoute, string? methodRoute)
{
var parts = new List<string>();
if (!string.IsNullOrEmpty(controllerRoute))
parts.Add(controllerRoute.Trim('/'));
if (!string.IsNullOrEmpty(methodRoute))
parts.Add(methodRoute.Trim('/'));
var template = "/" + string.Join("/", parts);
return template == "/" ? template : template.TrimEnd('/');
}
private static bool IsRouteMatch(string template, string path)
{
// 简化版路由匹配(支持路径参数如 /user/{id})
template = template.TrimEnd('/');
path = path.TrimEnd('/');
if (template == path)
return true;
// 转换路由模板为正则表达式
var pattern = "^" + Regex.Replace(template, @"\{[^}]+\}", @"([^/]+)") + "$";
return Regex.IsMatch(path, pattern, RegexOptions.IgnoreCase);
}
}
+315
View File
@@ -0,0 +1,315 @@
using System.Net;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Sharp.NetServer.Attributes;
using Sharp.NetServer.Middleware;
using Sharp.NetServer.Models;
using Sharp.NetServer.Routing;
using Sharp.NetServer.Extensions;
namespace Sharp.NetServer.Server;
/// <summary>
/// HTTP 服务器
/// </summary>
public class HttpServer
{
private readonly HttpListener _listener;
private readonly HttpServerOptions _options;
private readonly RouteTable _routeTable;
private readonly MiddlewarePipeline _pipeline;
private readonly IServiceProvider? _serviceProvider;
private readonly ILogger<HttpServer>? _logger;
private CancellationTokenSource? _cancellationTokenSource;
public HttpServer(HttpServerOptions options, IServiceProvider? serviceProvider = null)
{
_options = options;
_serviceProvider = serviceProvider;
_logger = serviceProvider?.GetService<ILogger<HttpServer>>();
_listener = new HttpListener();
_routeTable = new RouteTable();
_pipeline = new MiddlewarePipeline();
// 配置监听地址
ConfigureListener();
// 注册控制器
RegisterControllers();
// 配置中间件
ConfigureMiddleware();
}
/// <summary>
/// 启动服务器
/// </summary>
public async Task StartAsync(CancellationToken cancellationToken = default)
{
_cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_listener.Start();
_logger?.LogInformation("HTTP Server started on {Urls}", string.Join(", ", _options.ListenUrls));
// 启动请求处理循环
await ProcessRequestsAsync(_cancellationTokenSource.Token);
}
/// <summary>
/// 停止服务器
/// </summary>
public void Stop()
{
_cancellationTokenSource?.Cancel();
_listener.Stop();
_logger?.LogInformation("HTTP Server stopped");
}
private void ConfigureListener()
{
foreach (var url in _options.ListenUrls)
{
_listener.Prefixes.Add(url);
}
}
private void RegisterControllers()
{
foreach (var assembly in _options.ControllerAssemblies)
{
var controllerTypes = assembly.GetTypes()
.Where(t => t.IsClass && !t.IsAbstract &&
(t.GetCustomAttribute<ApiControllerAttribute>() != null ||
t.Name.EndsWith("Controller")));
foreach (var type in controllerTypes)
{
_routeTable.RegisterController(type);
_logger?.LogDebug("Registered controller: {ControllerName}", type.Name);
}
}
var routes = _routeTable.GetAllRoutes();
_logger?.LogInformation("Registered {Count} routes", routes.Count);
}
private void ConfigureMiddleware()
{
// 1. 异常处理(最外层)
if (_options.UseExceptionHandling)
{
_pipeline.Use(async (context, next) =>
{
var middleware = new ExceptionHandlingMiddleware(_serviceProvider?.GetService<ILogger<ExceptionHandlingMiddleware>>());
await middleware.InvokeAsync(context, next);
});
}
// 2. 日志记录
if (_options.UseLogging)
{
_pipeline.Use(async (context, next) =>
{
var middleware = new LoggingMiddleware(_serviceProvider?.GetService<ILogger<LoggingMiddleware>>());
await middleware.InvokeAsync(context, next);
});
}
// 3. CORS
if (_options.UseCors)
{
_pipeline.Use(async (context, next) =>
{
var middleware = new CorsMiddleware(_options.CorsOptions);
await middleware.InvokeAsync(context, next);
});
}
// 4. 认证
if (_options.UseAuthentication)
{
_pipeline.Use(async (context, next) =>
{
var authProvider = _serviceProvider?.GetService<Abstractions.IAuthenticationProvider>();
var middleware = new AuthenticationMiddleware(authProvider);
await middleware.InvokeAsync(context, next);
});
}
// 5. 授权
if (_options.UseAuthorization)
{
_pipeline.Use(async (context, next) =>
{
var middleware = new AuthorizationMiddleware();
await middleware.InvokeAsync(context, next);
});
}
// 6. 限流
if (_options.UseRateLimit)
{
_pipeline.Use(async (context, next) =>
{
var middleware = new RateLimitMiddleware();
await middleware.InvokeAsync(context, next);
});
}
// 7. 缓存
if (_options.UseResponseCache)
{
_pipeline.Use(async (context, next) =>
{
var cache = _serviceProvider?.GetService<IResponseCache>();
var middleware = new ResponseCacheMiddleware(cache);
await middleware.InvokeAsync(context, next);
});
}
// 8. 自定义中间件
foreach (var middlewareAction in _options.CustomMiddlewares)
{
_pipeline.Use(middlewareAction);
}
// 9. 路由处理(最内层)
_pipeline.Use(async (context, next) =>
{
await HandleRouteAsync(context);
});
}
private async Task ProcessRequestsAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
var listenerContext = await _listener.GetContextAsync();
// 异步处理请求(不等待)
_ = Task.Run(async () =>
{
try
{
await ProcessSingleRequestAsync(listenerContext, cancellationToken);
}
catch (Exception ex)
{
_logger?.LogError(ex, "Error processing request");
}
}, cancellationToken);
}
catch (HttpListenerException) when (cancellationToken.IsCancellationRequested)
{
// 服务器正在关闭
break;
}
catch (Exception ex)
{
_logger?.LogError(ex, "Error accepting request");
}
}
}
private async Task ProcessSingleRequestAsync(HttpListenerContext listenerContext, CancellationToken cancellationToken)
{
var context = new HttpContext(listenerContext)
{
CancellationToken = cancellationToken
};
try
{
// 执行中间件管道
await _pipeline.ExecuteAsync(context);
}
finally
{
try
{
context.Response.Close();
}
catch
{
// 忽略关闭异常
}
}
}
private async Task HandleRouteAsync(HttpContext context)
{
var route = _routeTable.FindRoute(context.Request.HttpMethod, context.Request.Url.AbsolutePath);
if (route == null)
{
// 404 Not Found
await WriteNotFoundResponseAsync(context);
return;
}
// 设置路由相关的上下文信息(供授权、限流等中间件使用)
context.Items["RouteInfo"] = route;
context.Items["RequireAuthorization"] = route.RequireAuthorization;
context.Items["AllowAnonymous"] = route.AllowAnonymous;
if (route.Roles != null)
context.Items["RequiredRoles"] = route.Roles;
if (route.Permissions != null)
context.Items["RequiredPermissions"] = route.Permissions;
if (route.RateLimitConfig != null)
context.Items["RateLimitConfig"] = route.RateLimitConfig;
if (route.CacheConfig != null)
context.Items["CacheConfig"] = route.CacheConfig;
// 创建控制器实例
var controller = CreateController(route.ControllerType);
// 调用控制器方法
try
{
var result = route.Method.Invoke(controller, new object[] { context });
if (result is Task task)
{
await task;
}
}
catch (Exception ex)
{
_logger?.LogError(ex, "Error invoking controller method: {Method}", route.Method.Name);
throw;
}
}
private object CreateController(Type controllerType)
{
// 尝试从 DI 容器获取
if (_serviceProvider != null)
{
var controller = _serviceProvider.GetService(controllerType);
if (controller != null)
return controller;
}
// 使用激活器创建
return Activator.CreateInstance(controllerType)!;
}
private static async Task WriteNotFoundResponseAsync(HttpContext context)
{
context.Response.StatusCode = 404;
context.Response.ContentType = "application/json; charset=utf-8";
var response = ResultExtensions.HttpFailure<object>("Route not found", 404);
var json = Common.Utils.JsonHelper.ToJson(response, useCompact: true);
var bytes = System.Text.Encoding.UTF8.GetBytes(json);
context.Response.ContentLength = bytes.Length;
await context.Response.OutputStream.WriteAsync(bytes);
}
}
@@ -0,0 +1,105 @@
using System.Reflection;
using Sharp.NetServer.Abstractions;
using Sharp.NetServer.Middleware;
namespace Sharp.NetServer.Server;
/// <summary>
/// HTTP 服务器配置选项
/// </summary>
public class HttpServerOptions
{
/// <summary>
/// 监听的 URL 列表
/// </summary>
public List<string> ListenUrls { get; set; } = new() { "http://localhost:5000/" };
/// <summary>
/// 控制器程序集列表
/// </summary>
public List<Assembly> ControllerAssemblies { get; set; } = new();
/// <summary>
/// 是否启用异常处理中间件
/// </summary>
public bool UseExceptionHandling { get; set; } = true;
/// <summary>
/// 是否启用日志记录中间件
/// </summary>
public bool UseLogging { get; set; } = true;
/// <summary>
/// 是否启用 CORS 中间件
/// </summary>
public bool UseCors { get; set; } = true;
/// <summary>
/// CORS 配置选项
/// </summary>
public CorsOptions CorsOptions { get; set; } = new();
/// <summary>
/// 是否启用认证中间件
/// </summary>
public bool UseAuthentication { get; set; } = false;
/// <summary>
/// 是否启用授权中间件
/// </summary>
public bool UseAuthorization { get; set; } = false;
/// <summary>
/// 是否启用限流中间件
/// </summary>
public bool UseRateLimit { get; set; } = true;
/// <summary>
/// 是否启用响应缓存中间件
/// </summary>
public bool UseResponseCache { get; set; } = true;
/// <summary>
/// 自定义中间件列表
/// </summary>
public List<Func<RequestDelegate, RequestDelegate>> CustomMiddlewares { get; set; } = new();
/// <summary>
/// 添加监听地址
/// </summary>
public HttpServerOptions AddListenUrl(string url)
{
if (!url.EndsWith('/'))
url += "/";
ListenUrls.Add(url);
return this;
}
/// <summary>
/// 添加控制器程序集
/// </summary>
public HttpServerOptions AddControllerAssembly(Assembly assembly)
{
ControllerAssemblies.Add(assembly);
return this;
}
/// <summary>
/// 添加自定义中间件
/// </summary>
public HttpServerOptions AddMiddleware(Func<RequestDelegate, RequestDelegate> middleware)
{
CustomMiddlewares.Add(middleware);
return this;
}
/// <summary>
/// 配置 CORS
/// </summary>
public HttpServerOptions ConfigureCors(Action<CorsOptions> configure)
{
configure(CorsOptions);
return this;
}
}
+9
View File
@@ -0,0 +1,9 @@
<Application x:Class="Repository.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Repository"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
+10
View File
@@ -0,0 +1,10 @@
using System.Windows;
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
+12
View File
@@ -0,0 +1,12 @@
<Window x:Class="Repository.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Repository"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
</Grid>
</Window>
+7
View File
@@ -0,0 +1,7 @@
namespace Sharp.Infrastructure
{
public class Class1
{
}
}
+42
View File
@@ -19,6 +19,20 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetClient", "NetClient\NetC
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetServer", "NetServer\NetServer.csproj", "{8223A4A8-DE17-4E26-A3EB-674E58B9C446}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Repository", "Repository\Repository.csproj", "{74D45E9E-A513-453F-B51D-5541D2857AB8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Config.Test", "..\..\test\Config.Test\Config.Test.csproj", "{F48331AE-8662-411E-B789-A0158A4A1F21}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sharp.Infrastructure", "Sharp.Infrastructure\Sharp.Infrastructure.csproj", "{10DDCB28-9DF5-4BC7-8A3E-AA92275BBB40}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Wpf", "Wpf\Wpf.csproj", "{FA8C6432-F42B-4A47-B0C1-60E1773E9CF7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetClient.Test", "..\..\test\NetClient.Test\NetClient.Test.csproj", "{DE83D16E-72D4-4E54-B4D2-17D9CF4E09DD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Log.Test", "..\..\test\Log.Test\Log.Test.csproj", "{B7E3FCE9-204B-47E9-B1F7-D0D08CFDBD44}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetServer.Test", "..\..\test\NetServer.Test\NetServer.Test.csproj", "{020997C0-FB5F-4222-8620-818840EF4447}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -57,6 +71,34 @@ Global
{8223A4A8-DE17-4E26-A3EB-674E58B9C446}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8223A4A8-DE17-4E26-A3EB-674E58B9C446}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8223A4A8-DE17-4E26-A3EB-674E58B9C446}.Release|Any CPU.Build.0 = Release|Any CPU
{74D45E9E-A513-453F-B51D-5541D2857AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{74D45E9E-A513-453F-B51D-5541D2857AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{74D45E9E-A513-453F-B51D-5541D2857AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{74D45E9E-A513-453F-B51D-5541D2857AB8}.Release|Any CPU.Build.0 = Release|Any CPU
{F48331AE-8662-411E-B789-A0158A4A1F21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F48331AE-8662-411E-B789-A0158A4A1F21}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F48331AE-8662-411E-B789-A0158A4A1F21}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F48331AE-8662-411E-B789-A0158A4A1F21}.Release|Any CPU.Build.0 = Release|Any CPU
{10DDCB28-9DF5-4BC7-8A3E-AA92275BBB40}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{10DDCB28-9DF5-4BC7-8A3E-AA92275BBB40}.Debug|Any CPU.Build.0 = Debug|Any CPU
{10DDCB28-9DF5-4BC7-8A3E-AA92275BBB40}.Release|Any CPU.ActiveCfg = Release|Any CPU
{10DDCB28-9DF5-4BC7-8A3E-AA92275BBB40}.Release|Any CPU.Build.0 = Release|Any CPU
{FA8C6432-F42B-4A47-B0C1-60E1773E9CF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FA8C6432-F42B-4A47-B0C1-60E1773E9CF7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FA8C6432-F42B-4A47-B0C1-60E1773E9CF7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FA8C6432-F42B-4A47-B0C1-60E1773E9CF7}.Release|Any CPU.Build.0 = Release|Any CPU
{DE83D16E-72D4-4E54-B4D2-17D9CF4E09DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DE83D16E-72D4-4E54-B4D2-17D9CF4E09DD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DE83D16E-72D4-4E54-B4D2-17D9CF4E09DD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DE83D16E-72D4-4E54-B4D2-17D9CF4E09DD}.Release|Any CPU.Build.0 = Release|Any CPU
{B7E3FCE9-204B-47E9-B1F7-D0D08CFDBD44}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B7E3FCE9-204B-47E9-B1F7-D0D08CFDBD44}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B7E3FCE9-204B-47E9-B1F7-D0D08CFDBD44}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B7E3FCE9-204B-47E9-B1F7-D0D08CFDBD44}.Release|Any CPU.Build.0 = Release|Any CPU
{020997C0-FB5F-4222-8620-818840EF4447}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{020997C0-FB5F-4222-8620-818840EF4447}.Debug|Any CPU.Build.0 = Debug|Any CPU
{020997C0-FB5F-4222-8620-818840EF4447}.Release|Any CPU.ActiveCfg = Release|Any CPU
{020997C0-FB5F-4222-8620-818840EF4447}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
+19
View File
@@ -0,0 +1,19 @@
using System;
using System.Threading.Tasks;
namespace Sharp.Wpf.Abstractions;
/// <summary>
/// Abstraction for UI thread Dispatcher operations.
/// </summary>
public interface IDispatcher
{
bool CheckAccess();
void Invoke(Action action);
T Invoke<T>(Func<T> func);
Task InvokeAsync(Action action);
Task<T> InvokeAsync<T>(Func<T> func);
Task InvokeAsync(Func<Task> action);
Task<T> InvokeAsync<T>(Func<Task<T>> func);
}
+10
View File
@@ -0,0 +1,10 @@
using System.Windows;
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
+94
View File
@@ -0,0 +1,94 @@
using System;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
namespace Sharp.Wpf.Behaviors;
/// <summary>
/// Attached behavior to route an event to an ICommand.
/// Usage:
/// <Button Content="Go"
/// behaviors:EventToCommand.EventName="Click"
/// behaviors:EventToCommand.Command="{Binding GoCommand}"
/// behaviors:EventToCommand.CommandParameter="{Binding}" />
/// </summary>
public static class EventToCommand
{
public static readonly DependencyProperty EventNameProperty = DependencyProperty.RegisterAttached(
"EventName", typeof(string), typeof(EventToCommand), new PropertyMetadata(null, OnEventNameChanged));
public static void SetEventName(DependencyObject element, string? value) => element.SetValue(EventNameProperty, value);
public static string? GetEventName(DependencyObject element) => (string?)element.GetValue(EventNameProperty);
public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
"Command", typeof(ICommand), typeof(EventToCommand), new PropertyMetadata(null));
public static void SetCommand(DependencyObject element, ICommand? value) => element.SetValue(CommandProperty, value);
public static ICommand? GetCommand(DependencyObject element) => (ICommand?)element.GetValue(CommandProperty);
public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.RegisterAttached(
"CommandParameter", typeof(object), typeof(EventToCommand), new PropertyMetadata(null));
public static void SetCommandParameter(DependencyObject element, object? value) => element.SetValue(CommandParameterProperty, value);
public static object? GetCommandParameter(DependencyObject element) => element.GetValue(CommandParameterProperty);
public static readonly DependencyProperty PassEventArgsToCommandProperty = DependencyProperty.RegisterAttached(
"PassEventArgsToCommand", typeof(bool), typeof(EventToCommand), new PropertyMetadata(false));
public static void SetPassEventArgsToCommand(DependencyObject element, bool value) => element.SetValue(PassEventArgsToCommandProperty, value);
public static bool GetPassEventArgsToCommand(DependencyObject element) => (bool)element.GetValue(PassEventArgsToCommandProperty);
private static readonly DependencyProperty HandlerProperty = DependencyProperty.RegisterAttached(
"__handler__", typeof(Delegate), typeof(EventToCommand));
private static void OnEventNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is not FrameworkElement element) return;
var oldHandler = (Delegate?)element.GetValue(HandlerProperty);
// detach previous
if (oldHandler != null)
{
var oldEventName = (string?)e.OldValue;
if (!string.IsNullOrWhiteSpace(oldEventName))
{
var evOld = element.GetType().GetEvent(oldEventName!, BindingFlags.Instance | BindingFlags.Public);
evOld?.RemoveEventHandler(element, oldHandler);
}
element.ClearValue(HandlerProperty);
}
var eventName = (string?)e.NewValue;
if (string.IsNullOrWhiteSpace(eventName)) return;
var ev = element.GetType().GetEvent(eventName!, BindingFlags.Instance | BindingFlags.Public);
if (ev == null) return;
// create handler: (object? sender, EventArgs e) => ExecuteCommand(...)
void Handler(object? sender, EventArgs args)
{
var command = GetCommand(element);
if (command == null) return;
var parameter = GetPassEventArgsToCommand(element) ? (object?)args : GetCommandParameter(element);
if (command.CanExecute(parameter)) command.Execute(parameter);
}
var method = typeof(EventToCommand).GetMethod(nameof(CreateHandler), BindingFlags.NonPublic | BindingFlags.Static);
var dlg = method!.Invoke(null, new object[] { ev.EventHandlerType!, (Action<object?, EventArgs>)Handler });
if (dlg is Delegate del)
{
ev.AddEventHandler(element, del);
element.SetValue(HandlerProperty, del);
}
}
// build delegate compatible with event signature from Action<object?, EventArgs>
private static Delegate CreateHandler(Type eventHandlerType, Action<object?, EventArgs> action)
{
var invoke = eventHandlerType.GetMethod("Invoke");
var parameters = invoke!.GetParameters();
return Delegate.CreateDelegate(eventHandlerType, action.Target!, action.Method);
}
}
+60
View File
@@ -0,0 +1,60 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Sharp.Wpf.Commands;
public interface IAsyncCommand : ICommand
{
Task ExecuteAsync(object? parameter = null, CancellationToken cancellationToken = default);
}
public sealed class AsyncCommand : IAsyncCommand
{
private readonly Func<CancellationToken, Task> _execute;
private readonly Func<bool>? _canExecute;
private bool _isExecuting;
public AsyncCommand(Func<Task> execute, Func<bool>? canExecute = null)
{
if (execute == null) throw new ArgumentNullException(nameof(execute));
_execute = _ => execute();
_canExecute = canExecute;
}
public AsyncCommand(Func<CancellationToken, Task> execute, Func<bool>? canExecute = null)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute;
}
public bool CanExecute(object? parameter)
{
if (_isExecuting) return false;
return _canExecute?.Invoke() ?? true;
}
public async void Execute(object? parameter)
{
await ExecuteAsync(parameter);
}
public async Task ExecuteAsync(object? parameter = null, CancellationToken cancellationToken = default)
{
if (!CanExecute(parameter)) return;
try
{
_isExecuting = true; RaiseCanExecuteChanged();
await _execute(cancellationToken).ConfigureAwait(false);
}
finally
{
_isExecuting = false; RaiseCanExecuteChanged();
}
}
public event EventHandler? CanExecuteChanged;
public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
+50
View File
@@ -0,0 +1,50 @@
using System;
using System.Windows.Input;
namespace Sharp.Wpf.Commands;
public class RelayCommand : ICommand
{
private readonly Action<object?> _execute;
private readonly Func<object?, bool>? _canExecute;
public RelayCommand(Action execute)
{
_execute = _ => execute();
}
public RelayCommand(Action<object?> execute, Func<object?, bool>? canExecute = null)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute;
}
public bool CanExecute(object? parameter) => _canExecute?.Invoke(parameter) ?? true;
public void Execute(object? parameter) => _execute(parameter);
public event EventHandler? CanExecuteChanged;
public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
public sealed class RelayCommand<T> : ICommand
{
private readonly Action<T?> _execute;
private readonly Func<T?, bool>? _canExecute;
public RelayCommand(Action<T?> execute, Func<T?, bool>? canExecute = null)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute;
}
public bool CanExecute(object? parameter) => _canExecute?.Invoke((T?)parameter) ?? true;
public void Execute(object? parameter) => _execute((T?)parameter);
public event EventHandler? CanExecuteChanged;
public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
@@ -0,0 +1,27 @@
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace Sharp.Wpf.Converters;
public sealed class BoolToVisibilityConverter : IValueConverter
{
public bool Inverse { get; set; }
public bool CollapseWhenHidden { get; set; } = true;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var b = value is bool v && v;
if (Inverse) b = !b;
if (b) return Visibility.Visible;
return CollapseWhenHidden ? Visibility.Collapsed : Visibility.Hidden;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var visible = value is Visibility v && v == Visibility.Visible;
return Inverse ? !visible : visible;
}
}
@@ -0,0 +1,26 @@
using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Windows.Data;
namespace Sharp.Wpf.Converters;
public sealed class EnumToDescriptionConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is not Enum e) return string.Empty;
var name = e.ToString();
var field = e.GetType().GetField(name);
var desc = field?.GetCustomAttributes(typeof(DescriptionAttribute), false)
.Cast<DescriptionAttribute>()
.FirstOrDefault()?.Description;
return desc ?? name;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> throw new NotSupportedException();
}
@@ -0,0 +1,15 @@
using System;
using System.Globalization;
using System.Windows.Data;
namespace Sharp.Wpf.Converters;
public sealed class InverseBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
=> value is bool b ? !b : value;
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> value is bool b ? !b : value;
}
@@ -0,0 +1,24 @@
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace Sharp.Wpf.Converters;
public sealed class NullOrEmptyToVisibilityConverter : IValueConverter
{
public bool Inverse { get; set; }
public bool CollapseWhenHidden { get; set; } = true;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var empty = value is null || (value is string s && string.IsNullOrEmpty(s));
var show = Inverse ? !empty : empty;
if (show) return Visibility.Visible;
return CollapseWhenHidden ? Visibility.Collapsed : Visibility.Hidden;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> throw new NotSupportedException();
}
@@ -0,0 +1,34 @@
using System;
namespace Sharp.Wpf.Exceptions;
public sealed class ExceptionHandlingOptions
{
/// <summary>
/// Show MessageBox on unhandled exceptions.
/// </summary>
public bool ShowDialog { get; set; } = true;
/// <summary>
/// If true, rethrow after handling (useful in Debug).
/// </summary>
public bool RethrowAfterHandle { get; set; } = false;
/// <summary>
/// Custom logger hook.
/// </summary>
public Action<Exception>? Log { get; set; }
= ex => System.Diagnostics.Debug.WriteLine(ex.ToString());
/// <summary>
/// Filter: return true to suppress handling (ignore).
/// </summary>
public Func<Exception, bool>? IgnoreFilter { get; set; }
= ex => false;
/// <summary>
/// Customize dialog title.
/// </summary>
public string DialogTitle { get; set; } = "Unexpected Error";
}
@@ -0,0 +1,17 @@
using System;
namespace Sharp.Wpf.Exceptions;
public interface IUiExceptionHandler
{
/// <summary>
/// Register global handlers for UI and background exceptions.
/// </summary>
void Register(ExceptionHandlingOptions? options = null);
/// <summary>
/// Remove registered handlers.
/// </summary>
void Unregister();
}
@@ -0,0 +1,89 @@
using System;
using System.Threading.Tasks;
using WpfMessageBox = System.Windows.MessageBox;
namespace Sharp.Wpf.Exceptions;
/// <summary>
/// WPF global exception handler wiring.
/// </summary>
public sealed class UiExceptionHandler : IUiExceptionHandler
{
private ExceptionHandlingOptions _options = new();
private bool _registered;
public void Register(ExceptionHandlingOptions? options = null)
{
if (_registered) return;
_options = options ?? new ExceptionHandlingOptions();
System.Windows.Application.Current.DispatcherUnhandledException += OnDispatcherUnhandledException;
AppDomain.CurrentDomain.UnhandledException += OnDomainUnhandledException;
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
_registered = true;
}
public void Unregister()
{
if (!_registered) return;
System.Windows.Application.Current.DispatcherUnhandledException -= OnDispatcherUnhandledException;
AppDomain.CurrentDomain.UnhandledException -= OnDomainUnhandledException;
TaskScheduler.UnobservedTaskException -= OnUnobservedTaskException;
_registered = false;
}
private void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
Handle(e.Exception);
e.Handled = true;
}
private void OnDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.ExceptionObject is Exception ex)
{
Handle(ex);
}
}
private void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
{
Handle(e.Exception);
e.SetObserved();
}
private void Handle(Exception ex)
{
try
{
if (_options.IgnoreFilter?.Invoke(ex) == true)
return;
_options.Log?.Invoke(ex);
if (_options.ShowDialog)
{
try
{
WpfMessageBox.Show(
ex.Message,
_options.DialogTitle,
System.Windows.MessageBoxButton.OK,
System.Windows.MessageBoxImage.Error);
}
catch
{
// ignore UI failures
}
}
}
finally
{
if (_options.RethrowAfterHandle)
{
// Re-throwing in global handlers is limited; deliberately no throw here.
// Consumers can choose to terminate the process after logging/dialog if desired.
}
}
}
}
+35
View File
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Sharp.Wpf.Mvvm;
/// <summary>
/// Base ViewModel implements INotifyPropertyChanged.
/// </summary>
public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable
{
public event PropertyChangedEventHandler? PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string? propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
private bool _isBusy;
public bool IsBusy
{
get => _isBusy;
set => SetProperty(ref _isBusy, value);
}
public virtual void Dispose() { }
}
+113
View File
@@ -0,0 +1,113 @@
Sharp.Wpf
=========
WPF 常用基础能力工具包,开箱即用:
- 全局异常处理:统一捕获 UI/后台异常,弹窗与日志钩子
- MVVM 基础:ViewModelBase、RelayCommand、AsyncCommand
- Dispatcher 封装:IDispatcher/DispatcherService
- 对话与文件对话:IDialogService、IFileDialogService
- 常用转换器:Bool/NullOrEmpty 可见性、布尔取反、枚举描述
- 附加行为:EventToCommand(事件转 ICommand)
- 窗口工具:WindowPlacement(位置/大小/状态持久化)
安装/引用
---------
- 作为仓库子项目引用:
```xml
<ItemGroup>
<ProjectReference Include="..\Wpf\Wpf.csproj" />
</ItemGroup>
```
- 或通过 NuGet(计划发布):`<PackageReference Include="Sharp.Wpf" Version="x.y.z" />`
快速上手
--------
1) 在 App 启动注册全局异常处理
```csharp
using System.Windows;
using Sharp.Wpf.Exceptions;
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
new UiExceptionHandler().Register(new ExceptionHandlingOptions
{
ShowDialog = true,
DialogTitle = "应用程序错误"
});
}
}
```
2) 在 XAML 启用窗口位置记忆、事件到命令、可见性转换器
```xml
<Window x:Class="Demo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:b="clr-namespace:Sharp.Wpf.Behaviors;assembly=Sharp.Wpf"
xmlns:w="clr-namespace:Sharp.Wpf.Windowing;assembly=Sharp.Wpf"
xmlns:conv="clr-namespace:Sharp.Wpf.Converters;assembly=Sharp.Wpf"
w:WindowPlacement.RememberPlacement="True"
w:WindowPlacement.PlacementId="MainWindow">
<Window.Resources>
<conv:BoolToVisibilityConverter x:Key="Bool2Vis" />
</Window.Resources>
<StackPanel>
<Button Content="点击弹窗"
b:EventToCommand.EventName="Click"
b:EventToCommand.Command="{Binding ShowDialogCommand}" />
<TextBlock Text="处理中..."
Visibility="{Binding IsBusy, Converter={StaticResource Bool2Vis}}"/>
</StackPanel>
</Window>
```
3) ViewModel 使用命令与对话服务
```csharp
using System;
using System.Threading.Tasks;
using Sharp.Wpf.Commands;
using Sharp.Wpf.Mvvm;
using Sharp.Wpf.Services;
public sealed class MainViewModel : ViewModelBase
{
private readonly IDialogService _dialog = new DialogService();
public IAsyncCommand ShowDialogCommand { get; }
public MainViewModel()
{
ShowDialogCommand = new AsyncCommand(async () =>
{
try { IsBusy = true; await Task.Delay(300); await _dialog.ShowInfoAsync("Hello!"); }
finally { IsBusy = false; }
});
}
}
```
4) 文件/文件夹对话
```csharp
var file = await new FileDialogService().OpenFileAsync("All Files|*.*");
var folder = await new FileDialogService().SelectFolderAsync();
```
注意
----
- 需要 `UseWPF` 与 `net8.0-windows` 目标框架。
- 本库同时启用 `UseWindowsForms` 以使用系统文件夹选择对话框。
- 若要禁用全局异常弹窗,可在 `ExceptionHandlingOptions` 中设置 `ShowDialog = false` 并仅使用 `Log` 钩子记录。
- `EventToCommand` 通过反射订阅事件,适用于大多数 Routed 事件;如需传递事件参数,可设置 `PassEventArgsToCommand="True"`。
+39
View File
@@ -0,0 +1,39 @@
using System.Threading.Tasks;
using WpfMessageBox = System.Windows.MessageBox;
namespace Sharp.Wpf.Services;
public interface IDialogService
{
Task ShowInfoAsync(string message, string? title = null);
Task ShowWarningAsync(string message, string? title = null);
Task ShowErrorAsync(string message, string? title = null);
Task<bool> ShowConfirmAsync(string message, string? title = null);
}
public sealed class DialogService : IDialogService
{
public Task ShowInfoAsync(string message, string? title = null)
{
WpfMessageBox.Show(message, title ?? "Info", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
return Task.CompletedTask;
}
public Task ShowWarningAsync(string message, string? title = null)
{
WpfMessageBox.Show(message, title ?? "Warning", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
return Task.CompletedTask;
}
public Task ShowErrorAsync(string message, string? title = null)
{
WpfMessageBox.Show(message, title ?? "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
return Task.CompletedTask;
}
public Task<bool> ShowConfirmAsync(string message, string? title = null)
{
var result = WpfMessageBox.Show(message, title ?? "Confirm", System.Windows.MessageBoxButton.OKCancel, System.Windows.MessageBoxImage.Question);
return Task.FromResult(result == System.Windows.MessageBoxResult.OK);
}
}
@@ -0,0 +1,64 @@
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using Sharp.Wpf.Abstractions;
namespace Sharp.Wpf.Services;
/// <summary>
/// Default Dispatcher implementation using Application.Current.Dispatcher.
/// </summary>
public sealed class DispatcherService : IDispatcher
{
private readonly Dispatcher _dispatcher;
public DispatcherService() : this(System.Windows.Application.Current?.Dispatcher ?? Dispatcher.CurrentDispatcher) { }
public DispatcherService(Dispatcher dispatcher)
{
_dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
}
public bool CheckAccess() => _dispatcher.CheckAccess();
public void Invoke(Action action)
{
if (action == null) throw new ArgumentNullException(nameof(action));
if (CheckAccess()) action(); else _dispatcher.Invoke(action);
}
public T Invoke<T>(Func<T> func)
{
if (func == null) throw new ArgumentNullException(nameof(func));
return CheckAccess() ? func() : _dispatcher.Invoke(func);
}
public Task InvokeAsync(Action action)
{
if (action == null) throw new ArgumentNullException(nameof(action));
if (CheckAccess()) { action(); return Task.CompletedTask; }
return _dispatcher.InvokeAsync(action).Task;
}
public Task<T> InvokeAsync<T>(Func<T> func)
{
if (func == null) throw new ArgumentNullException(nameof(func));
if (CheckAccess()) return Task.FromResult(func());
return _dispatcher.InvokeAsync(func).Task;
}
public Task InvokeAsync(Func<Task> action)
{
if (action == null) throw new ArgumentNullException(nameof(action));
if (CheckAccess()) return action();
return _dispatcher.InvokeAsync(action).Task.Unwrap();
}
public Task<T> InvokeAsync<T>(Func<Task<T>> func)
{
if (func == null) throw new ArgumentNullException(nameof(func));
if (CheckAccess()) return func();
return _dispatcher.InvokeAsync(func).Task.Unwrap();
}
}
@@ -0,0 +1,64 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using WinForms = System.Windows.Forms;
namespace Sharp.Wpf.Services;
public interface IFileDialogService
{
Task<string?> OpenFileAsync(string? filter = null, bool multiselect = false, string? initialDirectory = null);
Task<IReadOnlyList<string>> OpenFilesAsync(string? filter = null, string? initialDirectory = null);
Task<string?> SaveFileAsync(string? filter = null, string? defaultFileName = null, string? initialDirectory = null);
Task<string?> SelectFolderAsync(string? initialDirectory = null, string? description = null);
}
public sealed class FileDialogService : IFileDialogService
{
public Task<string?> OpenFileAsync(string? filter = null, bool multiselect = false, string? initialDirectory = null)
{
var dlg = new Microsoft.Win32.OpenFileDialog
{
Filter = filter ?? "All Files|*.*",
Multiselect = multiselect,
InitialDirectory = initialDirectory ?? string.Empty
};
var ok = dlg.ShowDialog() == true;
return Task.FromResult(ok ? dlg.FileName : null);
}
public Task<IReadOnlyList<string>> OpenFilesAsync(string? filter = null, string? initialDirectory = null)
{
var dlg = new Microsoft.Win32.OpenFileDialog
{
Filter = filter ?? "All Files|*.*",
Multiselect = true,
InitialDirectory = initialDirectory ?? string.Empty
};
var ok = dlg.ShowDialog() == true;
return Task.FromResult<IReadOnlyList<string>>(ok ? dlg.FileNames : []);
}
public Task<string?> SaveFileAsync(string? filter = null, string? defaultFileName = null, string? initialDirectory = null)
{
var dlg = new Microsoft.Win32.SaveFileDialog
{
Filter = filter ?? "All Files|*.*",
FileName = defaultFileName ?? string.Empty,
InitialDirectory = initialDirectory ?? string.Empty
};
var ok = dlg.ShowDialog() == true;
return Task.FromResult(ok ? dlg.FileName : null);
}
public Task<string?> SelectFolderAsync(string? initialDirectory = null, string? description = null)
{
using var dlg = new WinForms.FolderBrowserDialog
{
Description = description ?? "Select folder",
SelectedPath = initialDirectory ?? string.Empty,
ShowNewFolderButton = true
};
var ok = dlg.ShowDialog() == WinForms.DialogResult.OK;
return Task.FromResult(ok ? dlg.SelectedPath : null);
}
}
+118
View File
@@ -0,0 +1,118 @@
using System;
using System.IO;
using System.Reflection;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
namespace Sharp.Wpf.Windowing;
/// <summary>
/// Attached behavior to persist and restore Window size/position/state.
/// </summary>
public static class WindowPlacement
{
public static readonly DependencyProperty RememberPlacementProperty = DependencyProperty.RegisterAttached(
"RememberPlacement", typeof(bool), typeof(WindowPlacement), new PropertyMetadata(false, OnRememberPlacementChanged));
public static void SetRememberPlacement(Window element, bool value) => element.SetValue(RememberPlacementProperty, value);
public static bool GetRememberPlacement(Window element) => (bool)element.GetValue(RememberPlacementProperty);
public static readonly DependencyProperty PlacementIdProperty = DependencyProperty.RegisterAttached(
"PlacementId", typeof(string), typeof(WindowPlacement), new PropertyMetadata("default"));
public static void SetPlacementId(Window element, string value) => element.SetValue(PlacementIdProperty, value);
public static string GetPlacementId(Window element) => (string)element.GetValue(PlacementIdProperty);
private static void OnRememberPlacementChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is not Window win) return;
if ((bool)e.NewValue)
{
win.Loaded += OnLoaded;
win.Closing += OnClosing;
}
else
{
win.Loaded -= OnLoaded;
win.Closing -= OnClosing;
}
}
private static void OnLoaded(object sender, RoutedEventArgs e)
{
if (sender is not Window win) return;
var id = GetPlacementId(win);
var data = SettingsStore.Load<PlacementData>(id);
if (data == null) return;
win.WindowStartupLocation = WindowStartupLocation.Manual;
win.Left = Math.Max(data.Left, 0);
win.Top = Math.Max(data.Top, 0);
if (data.Width > 0) win.Width = data.Width;
if (data.Height > 0) win.Height = data.Height;
// do not restore Minimized
win.WindowState = data.State == WindowState.Minimized ? WindowState.Normal : data.State;
}
private static void OnClosing(object? sender, System.ComponentModel.CancelEventArgs e)
{
if (sender is not Window win) return;
var id = GetPlacementId(win);
var data = new PlacementData
{
Left = win.Left,
Top = win.Top,
Width = win.Width,
Height = win.Height,
State = win.WindowState
};
SettingsStore.Save(id, data);
}
private sealed class PlacementData
{
public double Left { get; set; }
public double Top { get; set; }
public double Width { get; set; }
public double Height { get; set; }
public WindowState State { get; set; }
}
private static class SettingsStore
{
private static readonly string Dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
Assembly.GetEntryAssembly()?.GetName().Name ?? "SharpWpf", "WindowPlacement");
public static T? Load<T>(string key)
{
try
{
var file = Path.Combine(Dir, key + ".json");
if (!File.Exists(file)) return default;
var json = File.ReadAllText(file);
return JsonSerializer.Deserialize<T>(json);
}
catch
{
return default;
}
}
public static void Save<T>(string key, T value)
{
try
{
Directory.CreateDirectory(Dir);
var file = Path.Combine(Dir, key + ".json");
var json = JsonSerializer.Serialize(value, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(file, json);
}
catch
{
// ignore persist errors
}
}
}
}
+4 -1
View File
@@ -1,11 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
<UseWindowsForms>true</UseWindowsForms>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyName>Sharp.Wpf</AssemblyName>
<RootNamespace>Sharp.Wpf</RootNamespace>
</PropertyGroup>
</Project>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>
@@ -1,21 +1,22 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("Wpf")]
[assembly: System.Reflection.AssemblyCompanyAttribute("Sharp.Wpf")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+727c83da2de202f20a4335ec3468eaf3cc1e8134")]
[assembly: System.Reflection.AssemblyProductAttribute("Wpf")]
[assembly: System.Reflection.AssemblyTitleAttribute("Wpf")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+237cbd8788e3abea9c8e3f9fdb46798cde43452b")]
[assembly: System.Reflection.AssemblyProductAttribute("Sharp.Wpf")]
[assembly: System.Reflection.AssemblyTitleAttribute("Sharp.Wpf")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
[assembly: System.Runtime.Versioning.TargetPlatformAttribute("Windows7.0")]
[assembly: System.Runtime.Versioning.SupportedOSPlatformAttribute("Windows7.0")]
@@ -1 +1 @@
fb9f88e326b448ad88559d63a18841f1cff56172b0130d180bfa4df4d8895b39
2f73c8423764d0eb8aeceea01d1feea6277f92837fb5fffa27cece3438cfc6e5
@@ -1,4 +1,10 @@
is_global = true
build_property.ApplicationManifest =
build_property.StartupObject =
build_property.ApplicationDefaultFont =
build_property.ApplicationHighDpiMode =
build_property.ApplicationUseCompatibleTextRendering =
build_property.ApplicationVisualStyles =
build_property.TargetFramework = net8.0-windows
build_property.TargetPlatformMinVersion = 7.0
build_property.UsingMicrosoftNETSdkWeb =
@@ -7,7 +13,7 @@ build_property.InvariantGlobalization =
build_property.PlatformNeutralAssembly =
build_property.EnforceExtendedAnalyzerRules =
build_property._SupportedPlatformList = Linux,macOS,Windows
build_property.RootNamespace = Wpf
build_property.RootNamespace = Sharp.Wpf
build_property.ProjectDir = D:\yuanll\sharp-basic\src\Sharp\Wpf\
build_property.EnableComHosting =
build_property.EnableGeneratedComInterfaceComImportInterop =
@@ -1,6 +1,8 @@
// <auto-generated/>
global using global::System;
global using global::System.Collections.Generic;
global using global::System.Drawing;
global using global::System.Linq;
global using global::System.Threading;
global using global::System.Threading.Tasks;
global using global::System.Windows.Forms;
@@ -8,7 +8,7 @@
"version": "1.0.0",
"restore": {
"projectUniqueName": "D:\\yuanll\\sharp-basic\\src\\Sharp\\Wpf\\Wpf.csproj",
"projectName": "Wpf",
"projectName": "Sharp.Wpf",
"projectPath": "D:\\yuanll\\sharp-basic\\src\\Sharp\\Wpf\\Wpf.csproj",
"packagesPath": "C:\\Users\\yllyo\\.nuget\\packages\\",
"outputPath": "D:\\yuanll\\sharp-basic\\src\\Sharp\\Wpf\\obj\\",
@@ -64,7 +64,7 @@
"Microsoft.NETCore.App": {
"privateAssets": "all"
},
"Microsoft.WindowsDesktop.App.WPF": {
"Microsoft.WindowsDesktop.App": {
"privateAssets": "none"
}
},
+2 -2
View File
@@ -15,7 +15,7 @@
"version": "1.0.0",
"restore": {
"projectUniqueName": "D:\\yuanll\\sharp-basic\\src\\Sharp\\Wpf\\Wpf.csproj",
"projectName": "Wpf",
"projectName": "Sharp.Wpf",
"projectPath": "D:\\yuanll\\sharp-basic\\src\\Sharp\\Wpf\\Wpf.csproj",
"packagesPath": "C:\\Users\\yllyo\\.nuget\\packages\\",
"outputPath": "D:\\yuanll\\sharp-basic\\src\\Sharp\\Wpf\\obj\\",
@@ -71,7 +71,7 @@
"Microsoft.NETCore.App": {
"privateAssets": "all"
},
"Microsoft.WindowsDesktop.App.WPF": {
"Microsoft.WindowsDesktop.App": {
"privateAssets": "none"
}
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"version": 2,
"dgSpecHash": "fFfyfvo8emI=",
"dgSpecHash": "EQ+I1wXrehg=",
"success": true,
"projectFilePath": "D:\\yuanll\\sharp-basic\\src\\Sharp\\Wpf\\Wpf.csproj",
"expectedPackageFiles": [],
+1 -1
View File
@@ -1 +1 @@
"restore":{"projectUniqueName":"D:\\yuanll\\sharp-basic\\src\\Sharp\\Wpf\\Wpf.csproj","projectName":"Wpf","projectPath":"D:\\yuanll\\sharp-basic\\src\\Sharp\\Wpf\\Wpf.csproj","outputPath":"D:\\yuanll\\sharp-basic\\src\\Sharp\\Wpf\\obj\\","projectStyle":"PackageReference","fallbackFolders":["D:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages"],"originalTargetFrameworks":["net8.0-windows"],"sources":{"C:\\Program Files (x86)\\Microsoft SDKs\\NuGetPackages\\":{},"https://api.nuget.org/v3/index.json":{}},"frameworks":{"net8.0-windows7.0":{"targetAlias":"net8.0-windows","projectReferences":{}}},"warningProperties":{"warnAsError":["NU1605"]},"restoreAuditProperties":{"enableAudit":"true","auditLevel":"low","auditMode":"direct"},"SdkAnalysisLevel":"9.0.200"}"frameworks":{"net8.0-windows7.0":{"targetAlias":"net8.0-windows","imports":["net461","net462","net47","net471","net472","net48","net481"],"assetTargetFallback":true,"warn":true,"frameworkReferences":{"Microsoft.NETCore.App":{"privateAssets":"all"},"Microsoft.WindowsDesktop.App.WPF":{"privateAssets":"none"}},"runtimeIdentifierGraphPath":"C:\\Program Files\\dotnet\\sdk\\9.0.203/PortableRuntimeIdentifierGraph.json"}}
"restore":{"projectUniqueName":"D:\\yuanll\\sharp-basic\\src\\Sharp\\Wpf\\Wpf.csproj","projectName":"Sharp.Wpf","projectPath":"D:\\yuanll\\sharp-basic\\src\\Sharp\\Wpf\\Wpf.csproj","outputPath":"D:\\yuanll\\sharp-basic\\src\\Sharp\\Wpf\\obj\\","projectStyle":"PackageReference","fallbackFolders":["D:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages"],"originalTargetFrameworks":["net8.0-windows"],"sources":{"C:\\Program Files (x86)\\Microsoft SDKs\\NuGetPackages\\":{},"https://api.nuget.org/v3/index.json":{}},"frameworks":{"net8.0-windows7.0":{"targetAlias":"net8.0-windows","projectReferences":{}}},"warningProperties":{"warnAsError":["NU1605"]},"restoreAuditProperties":{"enableAudit":"true","auditLevel":"low","auditMode":"direct"},"SdkAnalysisLevel":"9.0.200"}"frameworks":{"net8.0-windows7.0":{"targetAlias":"net8.0-windows","imports":["net461","net462","net47","net471","net472","net48","net481"],"assetTargetFallback":true,"warn":true,"frameworkReferences":{"Microsoft.NETCore.App":{"privateAssets":"all"},"Microsoft.WindowsDesktop.App":{"privateAssets":"none"}},"runtimeIdentifierGraphPath":"C:\\Program Files\\dotnet\\sdk\\9.0.203/PortableRuntimeIdentifierGraph.json"}}
+1 -1
View File
@@ -1 +1 @@
17630299672028072
17631078795867788