Interface-based client
NClient allows you to create clients not only for ASP.NET, but also any services.
To do this, you need to create an interface and additionally declare it with attributes from NClient.Annotations
:
[Path("api")]
public interface IProductServiceClient : INClient
{
[PostMethod("products")]
Task PostAsync([BodyParam] Product product);
}
If you add
INClient
interface, you will get additional NClient features: receive a full http response and change a resilience policy for requests (see features).
Now that you have an interface for the client, you can create a client:
IProductServiceClient client = NClientProvider
.Use<IProductServiceClient>(host: "http://localhost:8080")
.Build();
NClient.Annotations
They are very similar to attributes for ASP.NET controllers. Below there is a table with the existing attributes and their equivalents in ASP.NET.
NClient.InterfaceProxy.Attributes | Microsoft.AspNetCore.Mvc |
---|---|
ApiAttribute | ApiControllerAttribute |
PathAttribute | RouteAttribute |
GetMethodAttribute | HttpGetAttribute |
PostMethodAttribute | HttpPostAttribute |
PutMethodAttribute | HttpPutAttribute |
DeleteMethodAttribute | HttpDeleteAttribute |
QueryParamAttribute | FromQueryAttribute |
BodyParamAttribute | FromBodyAttribute |
RouteParamAttribute | FromRouteAttribute |
HeaderParamAttribute | FromHeaderAttribute |
Limitations
NClient attributes have some limitations:
Multiple attributes:
[GetMethod("weather"), GetMethod("weather/{date}")]
WeatherForecast GetAsync(DateTime date);
Exception NotSupportedNClientException
will be thrown.
Multiple body parameters:
[PostMethod]
void Post([BodyParam] WeatherForecast forecast, [BodyParam] DateTime date);
Exception NotSupportedNClientException
will be thrown.
Non primitive types in route template:
[PostMethod("weather/{forecast}")]
void PostAsync([BodyParam] WeatherForecast forecast);
Exception NotSupportedNClientException
will be thrown.
Non primitive types in headers:
[PostMethod]
void Post([HeaderParam] WeatherForecast forecast);
Exception NotSupportedNClientException
will be thrown.
Dictionaries of non primitive types in query:
[GetMethod]
void Get([QueryParam] Dictionary<int, WeatherForecast> forecasts);
Exception NotSupportedNClientException
will be thrown.
Arrays of non primitive types in query:
[GetMethod]
void Get([QueryParam] WeatherForecast[] forecasts);
Exception NotSupportedNClientException
will be thrown.