Asp .Net Core 系列:集成 Refit 和 RestEase 声明式 HTTP 客户端库

news/2024/5/19 21:08:11 标签: .netcore, http, 网络协议
http://www.w3.org/2000/svg" style="display: none;">

背景

.NET 中 有没有类似 Java 中 Feign 这样的框架?经过查找和实验,发现 在 .NET 平台上,虽然没有直接的 Feign 框架的端口,但是有一些类似的框架和库,它们提供了类似的功能和设计理念。下面是一些在 .NET 中用于声明式 HTTP 客户端的框架和库:

  1. Refit:
    Refit 是一个用于构建声明式、类型安全的 HTTP 客户端的库。它允许您通过定义接口来描述 HTTP API,并生成客户端代码。Refit 使用属性路由的方式定义 API 调用,类似于 Feign。它支持各种 HTTP 方法,如 GET、POST、PUT、DELETE 等,并支持异步操作。
    https://github.com/reactiveui/refit
  2. RestEase:
    RestEase 也是一个用于创建类型安全的 HTTP 客户端的库。它提供了类似于 Refit 的声明式 API 定义方式,允许您通过编写接口来描述 HTTP API。RestEase 支持各种 HTTP 方法,并提供了简单易用的 fluent API。
    https://github.com/canton7/RestEase
  3. Feign.net
    feign.net 是一个基于 .NET Standard 2.0 的库,它实现了与 Feign 类似的接口定义和调用方式。feign.net 支持异步操作,并提供了与 Refit 和 RestEase 类似的特性。
    https://github.com/daixinkai/feign.net

集成 Refit

要在 ASP.NET Core 中集成 Refit,首先需要安装 Refit 包。可以通过 NuGet 包管理器或者 .NET CLI 来完成:

dotnet add package Refit

接下来,您可以创建一个接口,用于定义对远程 API 的调用。例如:

using Microsoft.AspNetCore.Mvc;
using Refit;
using RefitDemo.Models;

namespace RefitDemo.WebApi
{

    public interface IWeatherForecastApi
    {
        [Get("/WeatherForecast/Get")]
        Task<string> GetWeatherForecast(string id);

        [Post("/WeatherForecast/Post")]
        Task<WeatherForecast> PostWeatherForecast(WeatherForecast weatherForecast);
    }
}

然后,您可以在 ASP.NET Core 应用程序中使用 Refit 客户端。一种常见的方法是将其注入到服务中,以便在需要时进行使用。例如,在 Startup.cs 中配置:

            builder.Services.AddRefitClient<IWeatherForecastApi>(new RefitSettings
            {
                ContentSerializer = new NewtonsoftJsonContentSerializer(
                     new JsonSerializerSettings
                     {
                         ContractResolver = new CamelCasePropertyNamesContractResolver()
                     }
              )
            }).ConfigureHttpClient(c => c.BaseAddress = new Uri("http://localhost:5237"));


    //封装
    builder.Services.AddRefitClients("RefitDemo.WebApi", "http://localhost:5237");

    public static class RefitExtensions
    {
        public static void AddRefitClients(this IServiceCollection services, string targetNamespace, string baseAddress, RefitSettings? refitSettings = null)
        {
            // 获取指定命名空间中的所有类型
            var types = Assembly.GetExecutingAssembly().GetTypes()
               .Where(t => t.Namespace == targetNamespace && t.IsInterface).ToList();

            foreach (var type in types)
            {
                services.AddRefitClient(type, refitSettings).ConfigureHttpClient(c => c.BaseAddress = new Uri(baseAddress));
            }
        }
    }

最后,您可以在需要使用 API 客户端的地方注入 IWeatherForecastApi 接口,并使用它来调用远程 API:

using Microsoft.AspNetCore.Mvc;
using RefitDemo.WebApi;

namespace RefitDemo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private readonly ILogger<WeatherForecastController> _logger;

        private readonly IWeatherForecastApi _weatherForecastApi;

        public WeatherForecastController(ILogger<WeatherForecastController> logger, IWeatherForecastApi weatherForecastApi)
        {
            _logger = logger;
            _weatherForecastApi = weatherForecastApi;
        }
        [HttpGet("GetWeatherForecast")]
        public async Task<string> GetWeatherForecast()
        {
            return await _weatherForecastApi.GetWeatherForecast("1111");
        }

        [HttpGet("PostWeatherForecast")]
        public async Task<WeatherForecast> PostWeatherForecast()
        {
            return await _weatherForecastApi.PostWeatherForecast(new WeatherForecast { Date = DateOnly.MaxValue,Summary = "1111" });
        }

        [HttpGet("Get")]
        public string Get(string id)
        {
            return id;
        }

        [HttpPost("Post")]
        public WeatherForecast Post(WeatherForecast weatherForecast)
        {
            return weatherForecast;
        }
    }
}

https://img-blog.csdnimg.cn/direct/f48784123cd241149073d8bfb65a94a8.png" alt="在这里插入图片描述" />

其它功能:https://github.com/reactiveui/refit?tab=readme-ov-file#table-of-contents

集成 RestEase

要在 ASP.NET Core 中集成 RestEase,首先需要安装 RestEase 包。可以通过 NuGet 包管理器或者 .NET CLI 来完成:

dotnet add package RestEase

接下来,您可以创建一个接口,用于定义对远程 API 的调用。例如:

using Microsoft.AspNetCore.Mvc;
using RestEase;
using RestEaseDemo.Models;


namespace RestEaseDemo.WebApi
{

    public interface IWeatherForecastApi
    {
        [Get("/WeatherForecast/Get")]
        Task<string> GetWeatherForecast(string id);

        [Post("/WeatherForecast/Post")]
        Task<WeatherForecast> PostWeatherForecast(WeatherForecast weatherForecast);
    }
}

然后,您可以在 ASP.NET Core 应用程序中使用 RestEase 客户端。一种常见的方法是将其注入到服务中,以便在需要时进行使用。例如,在 Startup.cs 中配置:

builder.Services.AddRestEaseClient<IWeatherForecastApi>("http://localhost:5252");

然后,您可以在 ASP.NET Core 应用程序中使用 RestEase 客户端。与 Refit 不同的是,RestEase 不需要额外的配置,您只需要直接使用接口即可。在需要使用 API 客户端的地方注入 IMyApi 接口,并使用它来调用远程 API:

using Microsoft.AspNetCore.Mvc;
using RestEaseDemo.WebApi;

namespace RestEaseDemo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private readonly ILogger<WeatherForecastController> _logger;

        private readonly IWeatherForecastApi _weatherForecastApi;

        public WeatherForecastController(ILogger<WeatherForecastController> logger, IWeatherForecastApi weatherForecastApi)
        {
            _logger = logger;
            _weatherForecastApi = weatherForecastApi;
        }
        [HttpGet("GetWeatherForecast")]
        public async Task<string> GetWeatherForecast()
        {
            return await _weatherForecastApi.GetWeatherForecast("1111");
        }

        [HttpGet("PostWeatherForecast")]
        public async Task<WeatherForecast> PostWeatherForecast()
        {
            return await _weatherForecastApi.PostWeatherForecast(new WeatherForecast { Date = DateOnly.MaxValue,Summary = "1111" });
        }

        [HttpGet("Get")]
        public string Get(string id)
        {
            return id;
        }

        [HttpPost("Post")]
        public WeatherForecast Post(WeatherForecast weatherForecast)
        {
            return weatherForecast;
        }
    }
}

其它功能:https://github.com/canton7/RestEase?tab=readme-ov-file#table-of-contents


http://www.niftyadmin.cn/n/5480739.html

相关文章

【ARM 裸机】汇编 led 驱动之基本语法

我们要编写的是 ARM 汇编&#xff0c;编译使用的是 gcc 交叉编译器&#xff0c;所以要符合 GNU 语法。 1、汇编指令 汇编由一条条指令构成&#xff0c;ARM 不能直接访问存储器&#xff0c;比如 RAM 中的数据&#xff0c;I.MX6UL 中的寄存器就是 RAM 类型的&#xff0c;我们用…

论文笔记:NEFTune: Noisy Embeddings Improve Instruction Finetuning

iclr 2024 reviewer 评分 5666 1 论文思路 论文的原理很简单&#xff1a;在finetune过程的词向量中引入一些均匀分布的噪声即可明显地提升模型的表现 2 方法评估

DSP笔记6-C2000的中断机制

中断Interrupt&#xff1a; 单核CPU顺序执行程序 中断源&#xff0c;引起计算机中断的时间&#xff0c;解放cpu&#xff0c;提高效率。 三个等级&#xff1a;CPU中断&#xff0c;PIE中断&#xff0c;外设中断 cpu定时器&#xff0c;EPWM&#xff0c;ADC&#xff0c;eCAP&…

如何合理利用Vue 3中的ref和reactive

&#x1f90d; 前端开发工程师、技术日更博主、已过CET6 &#x1f368; 阿珊和她的猫_CSDN博客专家、23年度博客之星前端领域TOP1 &#x1f560; 牛客高级专题作者、打造专栏《前端面试必备》 、《2024面试高频手撕题》 &#x1f35a; 蓝桥云课签约作者、上架课程《Vue.js 和 E…

专为苹果系统设计的精美可视化图表 | 开源日报 No.219

danielgindi/Charts Stars: 27.3k License: Apache-2.0 Charts 是为 iOS/tvOS/OSX 提供美观图表的开源项目&#xff0c;是跨平台 MPAndroidChart 在苹果设备上的实现。该项目提供了以下主要功能和优势&#xff1a; 支持 iOS、tvOS 和 macOS 平台使用 Swift 编写&#xff0c;可…

FFmpeg: 简易ijkplayer播放器实现--01项目简介

文章目录 项目介绍流程图播放器实现过程界面展示 项目介绍 此项目基于FFmeg中 ffplay.c进行二次开发&#xff0c;实现基本的功能&#xff0c;开发软件为Qt 项目优势&#xff1a; 参考ijkplayer播放器&#xff0c;实现UI界面和播放器核心进行解耦&#xff0c;容易添加其他功能…

网站SEO关键词规划时如何筛选出合适的关键词?

在网站SEO优化过程中&#xff0c;关键词布局是一个至关重要的环节。首先&#xff0c;我们需要确定核心关键词&#xff0c;然后通过各种策略和方法对关键词进行扩展。完成关键词扩展后&#xff0c;接下来的任务就是对这些扩展后的关键词进行筛选。那么&#xff0c;如何进行有效的…

idea中输入法被锁定如何清除

今天遇到一个问题&#xff1f;idea中输入法被锁定了&#xff0c;无论怎么切换输入法&#xff0c;切换中英文&#xff0c;在idea中输出的均为英文内容&#xff0c;该如何解决呢&#xff1f;&#xff08;idea官网&#xff1a;JetBrains: 软件开发者和团队的必备工具&#xff09; …