惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
The Blog of Author Tim Ferriss
Hugging Face - Blog
Hugging Face - Blog
F
Fortinet All Blogs
B
Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Security Blog
Microsoft Security Blog
Blog — PlanetScale
Blog — PlanetScale
月光博客
月光博客
腾讯CDC
小众软件
小众软件
G
Google Developers Blog
V
Visual Studio Blog
罗磊的独立博客
GbyAI
GbyAI
V
V2EX
大猫的无限游戏
大猫的无限游戏
H
Help Net Security
L
LangChain Blog
Engineering at Meta
Engineering at Meta
量子位
The GitHub Blog
The GitHub Blog
博客园 - 司徒正美
WordPress大学
WordPress大学
B
Blog RSS Feed

博客园 - lightsong

A YOLOv8-based project for real-time traffic density estimation. LoRA unsloth比transformer库本身的微调有什么优点? offline-llms +++ transformer + peft 微调 Train and Fine-Tune Sentence Transformers Models Symmetric vs. Asymmetric Semantic Search Hierarchical Navigable Small Worlds (HNSW) Vision Transformer + BentoML ML Serving/编排工具 Introducing Gemma 3 270M: The compact model for hyper-efficient AI Utopia -- 企业世界模型 trustgraph semantica semantica vs graphti Industrial-Strength Natural Language Processing seata reference with springboot and other valuable demo outbox pattern with springboot Saga pattern with springboot 基于 Sentence Transformers 的具体应用案例 Vault with Keycloak as workload IAM Ontology Reasoning System ADR Claude Code的hook The AI-Native SDLC playbook Introduction to Dapper Introduction to FluentValidation Introduction to AutoFixture Introduction to FluentAssertions Understanding Return Types: IEnumerable, IReadOnlyCollection, and List Introduction to Carter
Introduction to Refit
lightsong · 2026-08-28 · via 博客园 - lightsong

Introduction to Refit

https://jdaniel1987.github.io/Refit

这是一篇非常适合转载的技术博客文章。我已经为你整理好了完整的中文翻译,并按照你的要求,将原文中缺失的代码片段补全,同时保留了图片占位符的位置,方便你直接复制到博客编辑器中。


博客文章草稿

标题: Refit 简介:简化 .NET 中的 API 交互
作者: Jaime Daniel Delgado Ortega
发布时间: 2024年10月21日
阅读时间: 4 分钟


引言

在构建与外部 API 交互的应用程序时,高效地发起 HTTP 请求至关重要。Refit 是一个出色的库,它允许你使用特性(Attributes)来声明 API 接口,并自动生成 REST 客户端,从而极大地简化了这一过程。

什么是 Refit?

Refit 是一个用于 .NET 的 REST 库,它能将你的 REST API 变成一个实时接口。你无需手动编写 HttpClient 请求和处理反序列化,只需定义一个代表你 API 的接口,剩下的工作就交给 Refit 来完成。

Refit 的优势

  • 简单易用: Refit 让 .NET 中的 HTTP 通信变得极其简单,让你能专注于业务逻辑,而不是网络代码。
  • 自动反序列化: Refit 自动处理请求和响应的序列化与反序列化,减少了样板代码。
  • 使用特性进行配置: 通过在接口上使用特性,可以轻松定义 HTTP 方法(GET, POST, PUT, DELETE)和端点。
  • 与依赖注入集成: Refit 与 ASP.NET Core 的依赖注入(DI)系统无缝集成,允许你将 API 客户端注入到你的服务中。
  • 错误处理: 它提供内置支持,可以通过清晰且信息丰富的异常来处理错误响应。

开始使用 Refit

以下是将 Refit 集成到项目中的具体步骤。

1. 创建你的 API 控制器或使用外部 API

首先,你需要一个可供调用的 API。这里我们创建一个简单的 UsersController 作为示例。

[图片占位:项目结构或控制器代码截图]
(建议在此处插入一张显示 UsersController 代码的截图)

[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    private static List<User> users = new List<User>
    {
        new User { Id = 1, Name = "John Doe", Email = "john.doe@example.com" },
        new User { Id = 2, Name = "Jane Doe", Email = "jane.doe@example.com" }
    };

    [HttpGet]
    public IActionResult GetUsers()
    {
        return Ok(users);
    }

    [HttpGet("{id:int}")]
    public IActionResult GetUserById(int id)
    {
        var user = users.FirstOrDefault(u => u.Id == id);
        if (user == null)
        {
            return NotFound();
        }
        return Ok(user);
    }

    [HttpPost]
    public IActionResult CreateUser([FromBody] User user)
    {
        if (user == null)
        {
            return BadRequest();
        }

        user.Id = users.Count + 1;
        users.Add(user);
        return CreatedAtAction(nameof(GetUserById), new { id = user.Id }, user);
    }
}

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

注意: 你也可以使用 Refit 来调用任何外部 API。

2. 定义你的 API 接口

创建一个接口来代表你的 API 端点。使用 Refit 的特性来声明 HTTP 方法和路由。

using Refit;

public interface IUsersApi
{
    [Get("/users")]
    Task<List<User>> GetUsersAsync();

    [Get("/users/{id}")]
    Task<User> GetUserByIdAsync(int id);

    [Post("/users")]
    Task CreateUserAsync([Body] User user);
}

3. 在 Program.cs 中注册 Refit 客户端

Refit 可以轻松集成到 .NET 的依赖注入系统中。在 Program.cs 中使用以下代码注册你的 Refit 客户端:

builder.Services.AddRefitClient<IUsersApi>()
    .ConfigureHttpClient(c => c.BaseAddress = new Uri("https://yourapibaseaddress.com"));

对于外部 API,过程是相同的。你只需为 API 定义一个接口,并创建一个模型来映射响应数据。请注意,你不需要映射 API 响应中的每一个字段

builder.Services.AddRefitClient<IExternalApiExample>()
    .ConfigureHttpClient(c => c.BaseAddress = new Uri("https://externalbaseaddress.com"));
public class ExternalApiModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

4. 在你的应用程序中使用 Refit

现在,你可以将 Refit API 客户端注入到你的服务或控制器中,并用它来发起 API 调用。

public class UsersService
{
    private readonly IUsersApi _usersApi; // 你的 Refit 接口

    public UsersService(IUsersApi usersApi)
    {
        _usersApi = usersApi;
    }

    public async Task<List<User>> GetAllUsersAsync()
    {
        return await _usersApi.GetUsersAsync();
    }

    public async Task<User> GetUserByIdAsync(int id)
    {
        return await _usersApi.GetUserByIdAsync(id);
    }

    public async Task CreateUserAsync(User user)
    {
        await _usersApi.CreateUserAsync(user);
    }
}

5. 错误处理

Refit 提供了强大的错误处理支持。如果 API 调用失败,它会抛出一个包含请求和响应详细信息的 ApiException

try
{
    var user = await _usersApi.GetUserByIdAsync(1);
}
catch (ApiException ex)
{
    Console.WriteLine($"Request failed with status code {ex.StatusCode}");
}

6. 自定义请求

你可以使用特性来添加请求头、查询参数等。

[Get("/users")]
Task<List<User>> GetUsersAsync([AliasAs("limit")] int pageSize);

7. 发起认证请求

要在请求中包含认证令牌,你可以在 HttpClient 的设置中进行配置,或直接将其添加到请求头中。

builder.Services.AddRefitClient<IUsersApi>()
    .ConfigureHttpClient(c =>
    {
        c.BaseAddress = new Uri("https://api.example.com");
        c.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "your_token_here");
    });

结论

Refit 是一个功能极其强大的工具,它简化了在 .NET 中使用 RESTful API 的过程。通过使用简单的接口声明和特性,你可以消除样板式的 HTTP 请求代码,专注于构建应用程序的核心功能。今天就尝试在你的项目中使用 Refit,以简化你的 API 交互吧!


标签: #C# #.NET #Refit #API

(本文根据 CC BY 4.0 许可协议发布)

出处:http://www.cnblogs.com/lightsong/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。