RestEaseInterface is designed to enable fast, seamless, and strongly-typed communication between .NET applications using REST. It is built on top of RestEase, allowing you to create REST clients using a configured interface. RestEaseInterface complements this by generating corresponding endpoints with minimal APIs based on the same interface to handle incoming requests. Swagger supported.
Follow these steps to implement RestEaseInterface:
-
Create an Interface: Follow the RestEase documentation to design an interface. This interface should be accessible to both the client and server, as shown in the example project.
-
Client Initialization: On the client side, initialize the interface either directly or using HttpClientFactory.
-
Server-Side Implementation: On the server side (AspNetCore is required), create a class that implements the configured interface. This class will contain your business logic. Note: Do not create multiple classes for a single configured RestEase interface.
-
Server-Side Configuration in Startup/Program.cs:
- In the
IServiceCollection, use.UseRestEaseApiInterface(). This method searches for configured interfaces and classes at startup using reflection. - In the
IServiceProvider, use.AddRestEaseInterface(). This dynamically constructs minimal APIs based on these interfaces.
- In the
Shared code - available on server and client
using RestEase;
namespace RestEaseInterface.Example.Shared;
public interface IWeatherForecastController
{
[Get("GetWeatherForecast")]
IEnumerable<WeatherForecast> Get();
}
public class WeatherForecast
{
public DateOnly Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}Server code - Program.cs
using RestEaseInterface;
using RestEaseInterface.Swagger;
var builder = WebApplication.CreateBuilder(args);
// [...]
//Swagger implementation (optional)
builder.Services.AddSwaggerGen(x =>
{
x.EnableAnnotations();
x.DocumentFilter<RestEaseInterfaceSwaggerDocumentFilter>();
});
//RestEase implementation
builder.Services.AddRestEaseInterface();
var app = builder.Build();
// [...]
//RestEase implementation
app.UseRestEaseInterface(); Client code - Program.cs
using RestEase;
using RestEaseInterface.Example.Shared;
IWeatherForecastController api = RestClient.For<IWeatherForecastController>("http://localhost:<port>");
WeatherForecast[] weatherInfos = api.Get().Result.ToArray();
foreach (var weatherInfo in weatherInfos) {
Console.WriteLine($"Date: {weatherInfo.Date}. Summary: {weatherInfo.Summary}."
+ $"Temp°C: {weatherInfo.TemperatureC}. Temp-Fahrenheit: {weatherInfo.TemperatureF}");
}
Console.ReadLine();