Refit使用入门
前言
原文:Refit: The automatic type-safe REST library for .NET Core, Xamarin and .NET
百度翻译:Refit:适用于.NET Core、Xamarin和.NET的自动类型安全REST库
官方网站:https://github.com/reactiveui/refit
新建weapi项目并添加包Refit与Refit.HttpClientFactory
新建接口IGitHubApi.cs
using Refit;
namespace RefitDemo
{
public interface IGitHubApi
{
[Get("/WeatherForecast")]
Task<IEnumerable<WeatherForecast>> GetWeatherForecastList();
}
}
修改Program.cs
builder.Services
.AddRefitClient<IGitHubApi>()
.ConfigureHttpClient(c => c.BaseAddress = new Uri("https://localhost:7159"));
这里的7159改成你的项目端口
修改WeatherForecastController.cs
using Microsoft.AspNetCore.Mvc;
using Refit;
namespace RefitDemo.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
private readonly IGitHubApi _gitHubApi;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IGitHubApi gitHubApi)
{
_logger = logger;
_gitHubApi = gitHubApi;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
[HttpPost(Name = "GetTest")]
public async Task<IEnumerable<WeatherForecast>> GetTestAsync()
{
return await _gitHubApi.GetWeatherForecastList();
}
[HttpPost("GetTest1")]
public async Task<IEnumerable<WeatherForecast>> GetTest1Async()
{
var gitHubApi = RestService.For<IGitHubApi>("https://localhost:7159");
return await gitHubApi.GetWeatherForecastList();
}
}
}
这里代码就是这两种调用方式
[HttpPost(Name = "GetTest")]
public async Task<IEnumerable<WeatherForecast>> GetTestAsync()
{
return await _gitHubApi.GetWeatherForecastList();
}
[HttpPost("GetTest1")]
public async Task<IEnumerable<WeatherForecast>> GetTest1Async()
{
var gitHubApi = RestService.For<IGitHubApi>("https://localhost:7159");
return await gitHubApi.GetWeatherForecastList();
}
后面两个api就是Refit的调用结果
作者
吴晓阳(手机:13736969112微信同号)