NClient
:dizzy: NClient is an automatic type-safe .Net HTTP client that allows you to call web service API methods using annotated interfaces or controllers without boilerplate code.
Install / Use
/learn @nclient/NClientREADME
<img src="logo.png" width="50" height="50" align="left" alt="logo">NClient: automatic type-safe .NET HTTP client
NClient is an automatic, type-safe .NET HTTP client that can call web API methods using annotated interfaces. The main difference between NClient and its analogues is that NClient lets you annotate ASP.NET controllers via interfaces and then use these interfaces to create clients. This allows you get rid of unwanted dependencies on a client side and to reuse an API description in clients without boilerplate code.
// WebService.dll:
public class WeatherController : ControllerBase, IWeatherFacade {
public Task<Weather> GetAsync(string city, DateTime date) => ...;
}
// WebService.Facade.dll:
[HttpFacade, Path("api/[facade]")]
public interface IWeatherFacade {
[GetMethod("{city}")]
Task<Weather> GetAsync([RouteParam] string city, [QueryParam] DateTime date);
}
// Client.dll:
IWeatherFacade weatherFacade = NClientGallery.Clients.GetRest()
.For<IWeatherFacade>(host: "http://localhost:5000")
.WithSafeResilience(maxRetries: 3)
.Build();
Weather todaysWeather = await weatherFacade.GetAsync(city: "Chelyabinsk", date: DateTime.Today);
⭐ Give us a star
Do you like it? Support the development of this project and star this repo!
<a name="why" />🚀 Why use NClient?
Creating clients for web services can be quite a challenge because, in addition to data transfer, you need to implement query building, serialization, retry policies, mapping, error handling, and logging — not to mention the maintenance that comes with each update of your APIs. What if you could create clients with a fraction of the effort? This is exactly what NClient aims to achieve by allowing you to create clients declaratively.
By the way, you can contribute to the NClient, not just use it :smiley:
<a name="advantages" />💪 Advantages of NClient
- Integration with ASP.NET: Clients are available for all controllers out of the box.
- Generation of interfaces: Interfaces and DTOs are generated by the OpenAPI (Swagger) specification.
- Resilience: Resilience is provided by different strategies. There is Polly support.
- Serialization selection: Various serializers are available for use: System.Text.Json, Newtonsoft.JSON, System.XML, MessagePack, Protobuf, and your own.
- Auto validation of responses: Preset or custom validation of responses can be set.
- Auto mapping of responses: Native or your own models can be returned from the client instead of responses or DTOs.
- Extension using handlers: Handlers allow adding custom logic to the client parts.
- Extension using providers: The client functionality can be extended with native or your own providers.
- Easy error analysis: Your logger can be used in clients, and exceptions have all the required information for investigation.
- Easy to use with DI: Extension methods allow adding a client to a collection of services easily.
- Maximum flexibility: Any step of the request execution pipeline can be replaced with your own.
- [WIP] All types of applications: The library can be used on the backend (ASP.NET) and frontend (Blazor), and it is planned to support mobile/desktop (MAUI).
- [WIP] Various protocols: The REST protocol is provided as a ready-made solution, and it is planned to add GraphQL and RPC.
Features: Dynamic templated routing; Static routing; Dynamic query parameters; Collections as query parameters; Dynamic headers; Static headers; Dynamic body; Auto serialization and deserialization; HTTP/Transport context; Authentication; Asynchronous requests; Timeouts; Cancellation requests; Resilience policy; Response validation; Response mapping; File upload/download; Generic interfaces; Interface inheritance; Client factory; Versioning; Handling; Structured logging; Dependency injection support.
📖 Table of Contents
- How to install?
- Requirements
- How to use?
- Documentation
- Samples of applications
- Contributing
- NuGet Packages
🏁 How to install?
The easiest way is to install NClient package using Nuget:
dotnet add package NClient
<a name="requirements" />
🚧 Requirements
Use of the NClient library requires .NET Standard 2.0 or higher. The NClient controllers can be used with ASP.NET Core and .NET Core 3.1 target or higher.
<a name="usage" />👩🏼💻 How to use?
First, you have to create an interface describing the available endpoints and input/output data of a service via annotations. After that, you can select the required type of client in NClientGallery and then set additional settings for it if necessary.
Usage with third-party service
If you want to send requests to a third-party service, you should create an interface that describes the service you want to make requests to. Follow the steps below:
Step 1: Install NClient in the client project
dotnet add package NClient
Step 2: Install dotnet-nclient tool
dotnet tool install --global dotnet-nclient
Step 3: Generate the interface describing the API of the web service
dotnet nclient generate facade --api path/to/product-service-swagger.json --output MyProject/Client.cs
This command will generate an interface for the API using the OpenAPI (Swagger) specification:
[Path("api")]
public interface IProductServiceClient
{
[PostMethod("products")]
Task<Product> CreateAsync(Product product);
[GetMethod("products/{id}")]
Task<Product> GetAsync([RouteParam] int id);
}
If necessary, the interface can be changed. It is easy to do this because interface annotation is very similar to the annotation of controllers in ASP.NET. The PathAttribute defines the base path for all interface methods. The PostMethodAttribute specifies the type of HTTP method and the path to the endpoint.
Moreover, implicit annotations work as in ASP.NET controllers; for example, the BodyParamAttribute attribute will be implicitly set to the product parameter in the CreateAsync method. And certainly, route templates are also supported.
Read about all the features in the Annotation and Routing sections.
Step 4: Create the client
IProductServiceClient client = NClientGallery.Clients.GetRest()
.For<IProductServiceClient>(host: "http://localhost:8080")
.Build();
The GetRest method creates a REST client with System.Text.Json serialization and without a resilience policy.
Step 5 (optional): Configure the client
IProductServiceClient client = NClientGallery.Clients.GetRest()
.For<IProductServiceClient>(host: "http://localhost:8080")
.WithNewtonsoftJsonSerialization()
.WithResilience(x => x
.ForMethod(client => (Func<Product, Task<Product>>) client.CreateAsync)
.Use(maxRetries: 2, attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt))))
...
.Build();
After calling the For method, you can configure the client as needed. For example, you can replace the serializer with Newtonsoft.Json, add a retry policy, and so on. See the full documentation.
Step 6: Send an http request
// Equivalent to the following request:
// curl -X POST -H "Content-type: application/json" --data "{ id: 1 }" http://localhost:8080/api/products
Product product = await client.CreateAsync(new Product(name: "MyProduct"));
<a name="usage-aspnet" />
Usage with ASP.NET Core
If you want to generate a client for your ASP.NET web service, you need to extract an interface for your controller and annotate it with NClient attributes. These attributes are very similar to those used for ASP.NET controllers. Follow the steps below:
Step 1: Install NClient.AspNetCore package on server-side
dotnet add package NClient.AspNetCore
Step 2: Create the controlle
Related Skills
bluebubbles
339.1kUse when you need to send or manage iMessages via BlueBubbles (recommended iMessage integration). Calls go through the generic message tool with channel="bluebubbles".
gh-issues
339.1kFetch GitHub issues, spawn sub-agents to implement fixes and open PRs, then monitor and address PR review comments. Usage: /gh-issues [owner/repo] [--label bug] [--limit 5] [--milestone v1.0] [--assignee @me] [--fork user/repo] [--watch] [--interval 5] [--reviews-only] [--cron] [--dry-run] [--model glm-5] [--notify-channel -1002381931352]
healthcheck
339.1kHost security hardening and risk-tolerance configuration for OpenClaw deployments
node-connect
339.1kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
