Refit 简单用法
作者:青柚1943
- 2023-03-14 湖南
本文字数:1426 字
阅读完需:约 5 分钟
Refit:适用于 .NET Core、Xamarin 和 .NET 的自动类型安全 REST 库(详细请参考:Refit)
1、安装依赖
reift package
2、定义用户中心(http://localhost:34905)接口(自动生成方法体)
using Refit;
namespace AuthorityCenterService.RefitApi
{
//1、可以为所有接口统一添加静态Headers
//2、也可以单独为某个接口添加动态Headers
[Headers("User-Agent:App Center")]
public interface IUserApi
{
[Post("/user/new")]
Task CreateUserAsync(UserDto user, [Header("Authorization")] string authorization);
[Get("/user/{id}")]
Task<UserDto> GetUserAsync(Guid id);
[Delete("/user/{id}")]
Task DeleteUserAsync(Guid id, [Header("Authorization")] string authorization);
}
}
复制代码
3、在 appsetings.json 中增加 Refit 配置
"UserRefitOptions": {
"BaseUrl": "http://localhost:34905",
"TimeOut": 10,
"Headers": {
//...
}
复制代码
对应配置类
public class RefitApiSettings
{
public string BaseUrl { get; set; }
public TimeSpan TimeOut { get; set; }
public Dictionary<string, string> Headers { get; set; }
}
复制代码
4、.Net6 注册 Refit
/// <summary>
/// ServiceCollection扩展类(注册并配置Refit)
/// </summary>
public static class ServiceCollectionExtensions
{
public static IServiceCollection RegisterRefits(this IServiceCollection services, IConfiguration configuration)
{
var userRefitOption = configuration.GetSection("UserRefitOptions").Get<RefitApiSettings>();
#region Refit 6.x 默认序列化方式为 System.Text.Json,可以通过JsonSerializerOptions做Json序列化配置
var options = new JsonSerializerOptions()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase, //驼峰
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All), //unicode编码
WriteIndented = true //缩进
};
RefitSettings seetings = new()
{
ContentSerializer = new SystemTextJsonContentSerializer(options)
};
#Endregion
services.AddRefitClient<IUserApi>(seetings)
.ConfigureHttpClient(c =>
{
c.BaseAddress = new Uri(userRefitOption.BaseUrl);
c.DefaultRequestHeaders.Add("UserAgent", "InosticApp");
c.Timeout = userRefitOption.TimeOut;
});
return services;
}
}
复制代码
管道中注册服务(Program.cs)
builder.Services.RegisterRefits(builder.Configuration);
复制代码
5、应用(注入 IUserApi 即可调用远程服务的接口)
public class UserService
{
private readonly IUserApi _userApi;
public UserService(IUserApi userApi)
{
_userApi = userApi;
}
public async Task DeleteUserAsync(Guid id)
{
var user = await _userApi.GetUserAsync(id);
if (user == null)
{
throw new ApplicationException("用户不存在");
}
await _userApi.DeleteUserAsync(id);
}
}
复制代码
划线
评论
复制
发布于: 刚刚阅读数: 3
青柚1943
关注
生命不息,代码不止。 2020-08-04 加入
老街坊,小弄堂,是属于那年代白墙黑瓦的淡淡的忧伤。
评论