背景

.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://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

Asp .Net Core 系列:集成 Refit 和 RestEase 声明式 HTTP 客户端库的更多相关文章

  1. asp.net core 系列 18 web服务器实现

    一. ASP.NET Core Module 在介绍ASP.NET Core Web实现之前,先来了解下ASP.NET Core Module.该模块是插入 IIS 管道的本机 IIS 模块(本机是指 ...

  2. asp.net core 系列 16 Web主机 IWebHostBuilder

    一.概述 在asp.net core中,Host主机负责应用程序启动和生存期管理.host主机包括Web 主机(IWebHostBuilder)和通用主机(IHostBuilder).Web 主机是适 ...

  3. Asp.net Core 系列之--5.认证、授权与自定义权限的实现

    ChuanGoing 2019-11-24 asp.net core系列已经来到了第五篇,通过之前的基础介绍,我们了解了事件订阅/发布的eventbus整个流程,初探dapper ORM实现,并且简单 ...

  4. 【目录】asp.net core系列篇

    随笔分类 - asp.net core系列篇 asp.net core系列 68 Filter管道过滤器 摘要: 一.概述 本篇详细了解一下asp.net core filters,filter叫&q ...

  5. asp.net core系列 53 IdentityServer4 (IS4)介绍

    一.概述 在物理层之间相互通信必须保护资源,需要实现身份验证和授权,通常针对同一个用户存储.对于资源安全设计包括二个部分,一个是认证,一个是API访问. 1 认证 认证是指:应用程序需要知道当前用户的 ...

  6. 在 ASP.NET Core 中集成 Skywalking APM

    前言 大家好,今天给大家介绍一下如何在 ASP.NET Core 项目中集成 Skywalking,Skywalking 是 Apache 基金会下面的一个开源 APM 项目,有些同学可能会 APM ...

  7. 1.1专题介绍「深入浅出ASP.NET Core系列」

    大家好,我是IT人张飞洪,专注于.NET平台十年有余. 工作之余喜欢阅读和写作,学习的内容包括数据结构/算法.网络技术.Linux系统原理.数据库技术原理,设计模式.前沿架构.微服务.容器技术等等…… ...

  8. asp.net core系列 30 EF管理数据库架构--必备知识 迁移

    一.管理数据库架构概述 EF Core 提供两种主要方法来保持 EF Core 模型和数据库架构同步.一是以 EF Core 模型为基准,二是以数据库为基准. (1)如果希望以 EF Core 模型为 ...

  9. asp.net core系列 40 Web 应用MVC 介绍与详细示例

    一. MVC介绍 MVC架构模式有助于实现关注点分离.视图和控制器均依赖于模型. 但是,模型既不依赖于视图,也不依赖于控制器. 这是分离的一个关键优势. 这种分离允许模型独立于可视化展示进行构建和测试 ...

  10. asp.net core系列 39 Web 应用Razor 介绍与详细示例

    一. Razor介绍 在使用ASP.NET Core Web开发时, ASP.NET Core MVC 提供了一个新特性Razor. 这样开发Web包括了MVC框架和Razor框架.对于Razor来说 ...

随机推荐

  1. 【Azure 应用服务】在Azure App Service for Linux环境中,部署的Django应用,出现加载css、js等静态资源文件失败

    问题描述 在App Service for Linux环境中,部署Django应用,访问应用页面时候,出现css.js等静态资源文件加载失败问题. 浏览器Console提示的错误消息为: Refuse ...

  2. 如何在 C# 中以编程的方式将 CSV 转为 Excel XLSX 文件

    前言 Microsoft Excel的XLSX格式以及基于文本的CSV(逗号分隔值)格式,是数据交换中常见的文件格式.应用程序通过实现对这些格式的读写支持,可以显著提升性能.在本文中,小编将为大家介绍 ...

  3. 微信小程序开发:页面分享卡片、风格选择、通道启用等可配置

    上文说到,我们部署了定时任务,但是有个地方忘记在上文写了,这里补上,就是定时任务的超时时间问题,超时时间有7200秒: 我们改成7100秒: 再把云函数调用的云对象的超时时间也改下: 超时时间多一点, ...

  4. 酷睿i5与i7处理器有什么区别

    本文将深入解析酷睿i5与i7处理器的区别,帮助您做出明智的购买决策.购买笔记本之前,了解处理器相关知识至关重要. 处理器作为电脑的核心部件,其性能直接影响整机运行速度和效率. 市面上主流的笔记本处理器 ...

  5. XAF新手入门 - 应用程序模型(Application Model)

    应用程序模型不仅是XAF的核心,它更是XAF的最大特色,它自动收集XAF项目中的信息,用于生成不同平台的UI.由于应用程序模型在XAF中的重要性,官方文档对它的介绍比较详细,大家可以直接阅读官方文档 ...

  6. Zabbix Agent item监控项讲解

    前言 agent与snmp是Zabbix两种重要的监控方式,这一期主要介绍Zabbix Agent item监控项..Zabbix agent分为主动代理.被动代理,配置item类型时,可以选择需要的 ...

  7. SyntaxError: invalid property id(就是不支持ES6) (浏览器不支持对象...展开)

    SyntaxError: invalid property id(就是不支持ES6) (浏览器不支持对象...展开) 火狐55以后支持

  8. mockjs 前端写完 给后台调 mock.js | 改到2.0版本

    需求:最近活太忙了,实在是联调没有时间了,无奈又拾起来mockjs 1 安装mockjs npm install mockjs // 这是个只在开发的时候用,打包后就没有了,业务更安全 npm ins ...

  9. C++B树的实现

    B树的实现 今天我们就来实现以下B树,B树有什么特点那?我们来列举一下 每个非叶子节点中存放若干关键字数据,并且有若干指向儿子节点的指针.指针数目=关键字数目+1 根节点有最少1个,最多m-1个关键字 ...

  10. .NET Aspire Preview 4 发布!

    .NET Aspire是一个有态度的云原生应用开发框架,旨在改善生成.NET云原生应用的体验,并提供一组强大的工具来帮助你生成和运行分布式应用.它允许开发者快速创建属于自己的云原生应用,或改造已有的项 ...