OpenRobot.Framework.WebApiProxy 2.0.0

dotnet add package OpenRobot.Framework.WebApiProxy --version 2.0.0
                    
NuGet\Install-Package OpenRobot.Framework.WebApiProxy -Version 2.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="OpenRobot.Framework.WebApiProxy" Version="2.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="OpenRobot.Framework.WebApiProxy" Version="2.0.0" />
                    
Directory.Packages.props
<PackageReference Include="OpenRobot.Framework.WebApiProxy" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add OpenRobot.Framework.WebApiProxy --version 2.0.0
                    
#r "nuget: OpenRobot.Framework.WebApiProxy, 2.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package OpenRobot.Framework.WebApiProxy@2.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=OpenRobot.Framework.WebApiProxy&version=2.0.0
                    
Install as a Cake Addin
#tool nuget:?package=OpenRobot.Framework.WebApiProxy&version=2.0.0
                    
Install as a Cake Tool

OpenRobot.Framework.WebApiProxy

NuGet .NET

一个强大的 .NET 8.0 HTTP 客户端库,专为与基于 ABP 框架的 Web API 进行交互而设计。它为 HttpClient 提供了类型安全的包装器,内置支持多租户、JWT 授权、文件上传下载以及 SignalR 实时通信。

主要特性

  • 类型安全的 API 调用 - 强类型响应支持,减少运行时错误
  • ABP 框架集成 - 原生支持 ABP 的多租户、授权和响应格式
  • 文件操作 - 内置文件上传下载,支持进度跟踪
  • SignalR 实时通信 V2 - 全新 SignalR 客户端代理,原生自动重连、泛型事件注册、Result 模式调用、双向流式传输
  • UI 回调支持 - 可集成加载指示器和错误提示
  • System.Text.Json - 使用高性能的 .NET 内置 JSON 序列化
  • 简洁的 API - 链式配置,易于使用

安装

dotnet add package OpenRobot.Framework.WebApiProxy

或在 Visual Studio 的 NuGet 包管理器控制台中运行:

Install-Package OpenRobot.Framework.WebApiProxy

快速开始

1. 配置 API 连接

using OpenRobot.Framework.OpenApiProxy;

// 设置 API 主机地址
OpenApiFactory.SetBaseApiHost("https://api.example.com");

// 设置 JWT Bearer 令牌
OpenApiFactory.SetAuthorization("your-jwt-token");

// 设置租户 ID(多租户应用)
OpenApiFactory.SetTenantId("tenant-id-here");

2. 发起 HTTP 请求

using OpenRobot.Framework;

// GET 请求
var users = await OpenApiProxyFactory.GetRequest<List<UserDto>>("api/users");

// 带查询参数的 GET 请求
var result = await OpenApiProxyFactory.GetRequest("api/users", AutoLoading: true,
    new RequestParm("skipCount", 0),
    new RequestParm("maxResultCount", 10));

// POST 请求
var newUser = await OpenApiProxyFactory.PostRequest<UserDto>("api/users", new {
    Name = "张三",
    Email = "zhangsan@example.com"
});

// PUT 请求
await OpenApiProxyFactory.PutRequest("api/users/1", updateUserDto);

// DELETE 请求
await OpenApiProxyFactory.DeleteRequest("api/users/1");

使用示例

文件上传

await OpenApiProxyFactory.PostFileUploadRequest(
    "api/upload",
    @"C:\Documents\file.pdf",
    "file",  // 表单字段名
    AutoLoading: true,
    new RequestParm("category", "documents")
);

文件下载(带进度)

await OpenApiProxyFactory.GetFileDownloadRequest(
    "api/download/1",
    @"C:\Downloads\file.pdf",
    progress => Console.WriteLine($"下载进度: {progress}%")
);

SignalR 实时通信(V2 · 推荐)

using OpenRobot.Framework.WebApiProxy.Realtime;

// 1. 创建配置
var options = new SignalrProxyOptions
{
    ApiHost = "https://api.example.com",
    HubPath = "chathub",
    AccessTokenProvider = () => Task.FromResult("your-jwt-token"),
    Logger = (level, msg) => Console.WriteLine($"[{level}] {msg}")
};

// 2. 创建代理并启动
var proxy = new SignalrProxy(options);
proxy.StateChanged += args =>
    Console.WriteLine($"状态变化: {args.OldState} -> {args.NewState}");

await proxy.ConnectAsync();

// 3. 泛型事件注册(编译时类型安全)
proxy.On<string, string>("ReceiveMessage", (user, message) =>
{
    Console.WriteLine($"{user}: {message}");
    return Task.CompletedTask;
});

// 4a. 强类型调用(异常传播)
try
{
    var result = await proxy.InvokeAsync<UserDto>("GetUser", userId);
}
catch (SignalrConnectionException ex)
{
    Console.WriteLine($"调用失败 [{ex.ErrorType}]: {ex.Message}");
}

// 4b. Result 模式调用(不抛异常)
var safeResult = await proxy.TryInvokeAsync<UserDto>("GetUser", userId);
if (safeResult.Success)
    Console.WriteLine(safeResult.Data);
else
    Console.WriteLine($"失败: {safeResult.ErrorMessage}");

// 5. 断开连接
await proxy.DisconnectAsync();
// 或使用 await using 自动释放

短连接场景:

var options = new SignalrProxyOptions
{
    ApiHost = "https://api.example.com",
    HubPath = "datacube",
    AutoReconnect = false  // 短连接不需要重连
};

await using var proxy = new SignalrProxy(options);
await proxy.ConnectAsync();
var data = await proxy.InvokeAsync<DashboardDto>("GetLiveData");
// DisposeAsync 自动断开

SignalR 实时通信(V1 · 兼容保留)

// 定义事件处理器
public class ChatEventHandler : ISignalrOnEvent
{
    public string OnMethodName => "ReceiveMessage";
    public Type[] MethodTypes => new[] { typeof(string), typeof(string) };

    public Task Dowork(object?[] data)
    {
        var user = data[0]?.ToString();
        var message = data[1]?.ToString();
        Console.WriteLine($"{user}: {message}");
        return Task.CompletedTask;
    }
}

// 创建并启动连接
var proxy = new ClientSignalrProxy("https://api.example.com", "chathub", new ChatEventHandler());
proxy.ClientLogEvent += (level, message) => Console.WriteLine($"[{level}] {message}");

await proxy.Start();  // 内置自动重连

// 调用服务器方法
await proxy.InvokeProxy("SendMessage", new object[] { "你好", "世界" });

await proxy.Stop();

双向流式传输(V2)

// ===== 服务端 → 客户端(接收流) =====
var sub = await proxy.StreamAsync<SensorData>("GetSensorStream");
await foreach (var data in sub.ReadAllAsync())
    UpdateChart(data);

// ===== 客户端 → 服务端(上传流) =====
var upload = proxy.CreateUploadStream<SensorData>("IngestSensorData");
await upload.WriteAsync(new SensorData { Temp = 25.5 });
await upload.WriteAsync(new SensorData { Temp = 26.1 });
upload.Complete();

// 详细文档:docs/web-api-proxy/streaming-guide.md

UI 加载状态集成

public class UILoadingHandler : IOpenApiCustuomRequest
{
    public void StartRequest(string requestInfo)
    {
        // 显示加载指示器
        Application.Current.MainWindow.IsEnabled = false;
    }

    public void EndRequest()
    {
        // 隐藏加载指示器
        Application.Current.MainWindow.IsEnabled = true;
    }

    public void FailRequest(string error)
    {
        // 显示错误对话框
        MessageBox.Show($"请求失败: {error}");
    }
}

// 注册 UI 回调
OpenApiFactory.SetCustuomRequest(new UILoadingHandler());

配置选项

方法 说明 示例
SetBaseApiHost() 设置 API 主机地址 OpenApiFactory.SetBaseApiHost("https://api.example.com")
SetAuthorization() 设置 JWT Bearer 令牌 OpenApiFactory.SetAuthorization("your-token")
SetTenantId() 设置 ABP 租户 ID OpenApiFactory.SetTenantId("tenant-1")
SetHttpVersion() 设置 HTTP 版本 OpenApiFactory.SetHttpVersion(2, 0)
SetCustuomRequest() 设置请求回调处理器 OpenApiFactory.SetCustuomRequest(new MyHandler())

ABP 框架集成

本库自动处理 ABP 框架的特定请求头和响应格式:

自动添加的请求头

  • Abp.TenantId: 多租户标识符
  • Authorization: Bearer 令牌
  • .AspNetCore.Culture: 文化设置(默认为 "zh-Hans")
  • Cache-Control: 设置为 "no-cache"

支持的 ABP 响应格式

{
  "success": true,
  "result": { ... },
  "error": {
    "code": 0,
    "message": "错误信息",
    "details": "详细信息",
    "validationErrors": "..."
  },
  "targetUrl": "",
  "unAuthorizedRequest": false
}

依赖项

包名 版本 用途
Microsoft.AspNetCore.SignalR.Client 10.0.10 SignalR 客户端
Microsoft.AspNetCore.SignalR.Protocols.MessagePack 10.0.10 MessagePack 二进制协议
System.Text.Json 内置 JSON 序列化(驼峰命名)

系统要求

  • .NET 8.0 或更高版本

API 参考

主要类

类名 命名空间 说明
OpenApiFactory OpenRobot.Framework.OpenApiProxy 配置类
OpenApiProxyFactory OpenRobot.Framework HTTP 请求工厂
SignalrProxy OpenRobot.Framework.WebApiProxy.Realtime SignalR 客户端 V2(推荐)
ISignalrProxy OpenRobot.Framework.WebApiProxy.Realtime SignalR 客户端抽象接口
SignalrProxyOptions OpenRobot.Framework.WebApiProxy.Realtime SignalR 配置对象
SignalrInvokeResult / SignalrInvokeResult<T> OpenRobot.Framework.WebApiProxy.Realtime 安全调用返回结果
SignalrConnectionException OpenRobot.Framework.WebApiProxy.Realtime 连接异常
SignalrErrorType OpenRobot.Framework.WebApiProxy.Realtime 错误类型枚举
ConnectionStateChangedEventArgs OpenRobot.Framework.WebApiProxy.Realtime 连接状态变化事件参数
ISignalrStreamSubscription<T> OpenRobot.Framework.WebApiProxy.Realtime 服务端→客户端 流订阅(自动重连)
ISignalrUploadStream<T> OpenRobot.Framework.WebApiProxy.Realtime 客户端→服务端 流上传(自动重连)
ClientSignalrProxy OpenRobot.Framework.WebApiProxy.Realtime SignalR 客户端 V1(兼容)
RequestResult<T> OpenRobot.Framework.OpenApiProxy 响应结果
IOpenApiCustuomRequest OpenRobot.Framework.OpenApiProxy 请求回调接口

数据模型

// 请求参数
public class RequestParm
{
    public string Name { get; set; }
    public object Value { get; set; }
}

// 错误信息
public class RequestError
{
    public int Code { get; set; }
    public string Message { get; set; }
    public string Details { get; set; }
    public string ValidationErrors { get; set; }
}

// 响应结果
public class RequestResult<T>
{
    public bool Success { get; set; }
    public T Result { get; set; }
    public RequestError Error { get; set; }
    public string TargetUrl { get; set; }
    public bool UnAuthorizedRequest { get; set; }
}

许可证

本项目采用 MIT 许可证。

作者

OpenRobot

设计文档

  • docs/web-api-proxy/streaming-guide.md — 双向流式传输完整指南(TCP 采集 + Hub 示例 + 性能优化)

版本历史

2.0.0 (2026-07-20)

SignalrProxy V2 全新设计:

  • 配置对象模式SignalrProxyOptions 统一管理连接、重连、认证、日志,通过属性初始化器设值
  • 原生自动重连:基于 SignalR WithAutomaticReconnect,支持自定义退避延迟和最大重试次数
  • 线程安全SemaphoreSlim 保护 ConnectAsync/DisconnectAsyncConcurrentDictionary 管理事件订阅
  • 资源释放IAsyncDisposable 规范释放所有资源,await using 友好
  • 状态变化通知StateChanged 事件(Disconnected → Connecting → Connected → Reconnecting → Disconnected),ConnectionStateChangedEventArgs 含 OldState/NewState/Reason/Timestamp
  • Token 刷新AccessTokenProvider 工厂委托,每次请求(含重连)自动调用获取最新 Token

双向流式传输(自动重连):

  • 服务端→客户端StreamAsync<T>()ISignalrStreamSubscription<T>
    • Pull 模式:await foreach (var item in sub.ReadAllAsync()),断线重连后自动续传
    • Push 模式:sub.Subscribe(onNext, onError, onCompleted)
  • 客户端→服务端CreateUploadStream<T>()ISignalrUploadStream<T>
    • 线程安全 WriteAsync(),可从 TCP 采集线程直接调用
    • 内部 Channel 缓冲,断线重连后自动续传(at-least-once 语义)
  • 全链路流式管道:客户端 A(TCP采集)→ 流式上传 → Hub(ChannelReader 接收 + ChannelWriter 广播)→ 流式下载 → 客户端 C
  • 完整文档与 TCP 采集示例:streaming-guide.md,含 500μs 高频采样的批量优化方案

调用 API:

  • 强类型调用InvokeAsync<T>() 异常直接传播,调用方 try/catch 处理
  • Result 模式TryInvokeAsync<T>() 返回 SignalrInvokeResult<T>(Success / Data / ErrorType / ErrorMessage),不抛异常
  • 泛型事件注册On<T1..T8>(methodName, handler) 编译时类型安全,RemoveHandler(methodName) 批量取消订阅
  • 长连接/短连接双模式ConnectAsyncDisconnectAsync 可多次使用,await using 自动释放

错误体系:

  • SignalrErrorType 枚举:NotConnected / Timeout / ConnectionLost / ServerError / HubMethodNotFound / Unknown
  • SignalrConnectionException:含 ErrorType 属性,区分连接异常和服务端异常
  • SignalrInvokeResult / SignalrInvokeResult<T>:Success / ErrorType / ErrorMessage / Data

V1 兼容保留:

  • ClientSignalrProxyISignalrOnEventProtoLogLevel 完全不动
  • SignalrProxyOptions.HubEvents 仍接受 ISignalrOnEvent[],V1 事件处理器无需修改即可在新代理中使用

1.0.0

  • 首次发布:基于 ABP 框架的 .NET 8.0 HTTP 客户端库
  • HTTP 请求代理:GET/POST/PUT/DELETE 类型安全封装,RequestResult<T> 统一响应格式
  • 文件操作PostFileUploadRequest 分段上传,GetFileDownloadRequest 进度回调
  • ABP 框架集成Abp.TenantId 多租户、JWT Bearer 授权、AjaxResponse 格式自动解析
  • UI 回调IOpenApiCustuomRequest 请求生命周期钩子(StartRequest / EndRequest / FailRequest)
  • SignalR V1 客户端ClientSignalrProxy 手动轮询重连,ISignalrOnEvent 运行时类型事件注册

反馈与贡献

欢迎通过以下方式提供反馈:

  • 提交 Issue
  • 发起 Pull Request
  • 联系维护者

注意: 本库专为与 ABP 框架后端配合使用而设计。如需与其他 API 交互,可能需要额外的适配工作。

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.0.0 162 7/27/2026
1.0.0 115 4/16/2026