安装指南

RestClient.Net 以 NuGet 包形式分发。本指南涵盖所有可用包的安装方法。

前置条件

  • .NET 8.0 或更高版本
  • 代码编辑器(推荐使用 Visual Studio、VS Code 或 Rider)
  • 对 C# 和 HttpClient 有基本了解

核心包

主包提供带有 Result 类型的 HttpClient 扩展方法:

dotnet add package RestClient.Net

自动包含以下内容:

  • HttpClient 扩展方法(GetAsyncPostAsync 等)
  • Result<TSuccess, HttpError<TError>> 类型
  • AbsoluteUrl 类型及扩展
  • Exhaustion 分析器,用于编译时穷尽性检查

包引用(csproj)

或者直接添加到 .csproj 文件:

<ItemGroup>
  <PackageReference Include="RestClient.Net" Version="6.*" />
</ItemGroup>

附加包

OpenAPI 生成器

从 OpenAPI 3.x 规范生成类型安全的客户端:

dotnet add package RestClient.Net.OpenApiGenerator

MCP 服务器生成器

生成用于 Claude Code 集成的模型上下文协议服务器:

dotnet add package RestClient.Net.McpGenerator

独立 Exhaustion 分析器

如果只需要穷尽性分析器而不需要 REST 客户端:

dotnet add package Exhaustion

快速设置

安装后,在项目根目录创建 GlobalUsings.cs 文件:

// GlobalUsings.cs
global using System.Net.Http.Json;
global using System.Text.Json;
global using RestClient.Net;
global using Urls;

为每个使用的模型类型添加类型别名,以实现更简洁的模式匹配:

// User 模型与 ApiError 的示例
global using OkUser = Outcome.Result<User, Outcome.HttpError<ApiError>>
    .Ok<User, Outcome.HttpError<ApiError>>;

global using ErrorUser = Outcome.Result<User, Outcome.HttpError<ApiError>>
    .Error<User, Outcome.HttpError<ApiError>>;

global using ResponseErrorUser = Outcome.HttpError<ApiError>.ErrorResponseError;

global using ExceptionErrorUser = Outcome.HttpError<ApiError>.ExceptionError;

验证安装

创建一个简单的测试来验证一切正常工作:

using System.Text.Json;
using RestClient.Net;
using Urls;

// 定义模型
record Post(int UserId, int Id, string Title, string Body);
record ErrorResponse(string Message);

// 创建 HttpClient
using var httpClient = new HttpClient();

// 发起测试调用
var result = await httpClient.GetAsync(
    url: "https://jsonplaceholder.typicode.com/posts/1".ToAbsoluteUrl(),
    deserializeSuccess: async (content, ct) =>
        await content.ReadFromJsonAsync<Post>(ct) ?? throw new Exception("空响应"),
    deserializeError: async (content, ct) =>
        await content.ReadFromJsonAsync<ErrorResponse>(ct) ?? new ErrorResponse("未知错误")
);

Console.WriteLine(result switch
{
    Outcome.Result<Post, Outcome.HttpError<ErrorResponse>>.Ok(var post) =>
        $"成功: {post.Title}",
    Outcome.Result<Post, Outcome.HttpError<ErrorResponse>>.Error(var error) =>
        $"错误: {error}",
});

IDE 支持

Visual Studio

Exhaustion 分析器开箱即用。对于非穷尽的 switch 表达式,您将看到编译错误。

VS Code

安装 C# 扩展(ms-dotnettools.csharp)以获得完整的分析器支持。

Rider

JetBrains Rider 完全支持 Roslyn 分析器,包括 Exhaustion。

下一步