Geko.HttpClientService
An easy way to make HTTP requests to JSON endpoints, with IdentityServer4 integration.
Install / Use
/learn @georgekosmidis/Geko.HttpClientServiceREADME
An easy way to make HTTP requests to JSON endpoints, with IdentityServer4 integration
An almost 2x times faster fluent HTTP request service, build to simplify the communication with JSON endpoints, by automatically handling serialization / deserialization. Authenticated requests towards protected by IdentityServer4 resources are done in a simple compact way.
Add it to the service collection in Startup.cs
services.AddHttpClientService();
//Or if the resources are behind an IdentityServer4
services.AddHttpClientService(
.Configure<ClientCredentialsOptions>(Configuration.GetSection(nameof(ClientCredentialsOptions)));
Calls can be easy as that :)
var responseObject = await _requestServiceFactory
//Create a instance of the service
.CreateHttpClientService()
//GET and deserialize the response body to IEnumerable<Customers>
.GetAsync<IEnumerable<Customers>>("https://api/customers");
Check the Getting started guide for more details!
Table of Contents
- Getting started
- How to setup an Access Token Request
- More info on how to serialize request, deserialize response
- Configuring the colleration id
- Contributing
Getting started
Getting started with Geko.HttpClientService is rather easy, since you only need three things:
- Install the nuget package Geko.HttpClientService
- Optionally, provide the options to request an access token from an IdentityServer4 service in the
appsettings.json - Register the service in
Startup.cs
It's a nuget package
Install the Geko.HttpClientService nuget package, using any of your favorite ways.
Optionally, set the IdentityServer4 Access Token Request Options
Add the IdentityServer4 Access Token Request Options to your appsettings.json (the configuration section should always be or end with ClientCredentialsOptions):
"ClientCredentialsOptions": {
"Address": "https://demo.identityserver.io/connect/token",
"ClientId": "m2m",
"ClientSecret": "secret",
"Scope": "api"
}
// The values above are part of the demo offered in https://demo.identityserver.io/
Register the service
Register the service In StartUp.cs in ConfigureServices(IServiceCollection services):
services.AddHttpClientService()
//Optional, set it if you have ClientCredentialsOptions or PasswordOptions
.Configure<ClientCredentialsOptions>(Configuration.GetSection(nameof(ClientCredentialsOptions)));
You are done
Request the IHttpClientServiceFactory wherever you want to make the authenticated requests:
using Geko.HttpClientService.Extensions;
[ApiController]
[Route("customers")]
public class CustomerController : ControllerBase
{
//Request the IHttpClientServiceFactory instance in your controller or service
private readonly IHttpClientServiceFactory _requestServiceFactory;
public CustomerController(IHttpClientServiceFactory requestServiceFactory){
_requestServiceFactory = requestServiceFactory;
}
[HttpGet]
public async Task<IActionResult> Get(){
//Make the request
var responseObject = await _requestServiceFactory
//Create a instance of the service
.CreateHttpClientService()
//GET and deserialize the response body to IEnumerable<Customers>
.GetAsync<IEnumerable<Customers>>("https://api/customers");
//Do something with the results
if (!responseObject.HasError)
{
var customers = responseObject.BodyAsType;
return Ok(customers);
}
else
{
var httpStatusCode = responseObject.StatusCode;
var errorMessage = responseObject.Error;
return StatusCode((int)httpStatusCode, errorMessage);
}
}
}
Configuring the service from startup following the Options Pattern is the simpler way, but there are more ways HTTP verbs supported are: GET, POST, PUT, DELETE, PATCH and HEAD.
Wanna study more?
You can also take a look at the Documentation for technical details, check the features sample or a more complete one.
How to setup an Access Token Request
The library supports multiple ways for setting up the necessary options for retrieving an access token. Upon success of retrieving one, the result is cached until the token expires; that means that a new request to a protected resource does not necessarily means a new request for an access token.
Currently, the library only supports
ClientCredentialsTokenRequestandPasswordTokenRequest.
.SetIdentityServerOptions<TOptions>(TOptions)
Setup IdentityServer options by passing a ClientCredentialsOptions or PasswordOptions directly to the SetIdentityServerOptions:
//...
.SetIdentityServerOptions(
new PasswordOptions
{
Address = "https://demo.identityserver.io/connect/token",
ClientId = "ClientId",
ClientSecret = "ClientSecret",
Scope = "Scope",
Username = "Username",
Password = "Password"
}
)
//...
.SetIdentityServerOptions<TOptions>(IOptions<TOptions>)
Setup IdentityServer options using the options pattern (read more about the options pattern in Microsoft Docs):
Startup.cs
//...
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddHttpClientService()
.AddSingleton<IProtectedResourceService, ProtectedResourceService>()
.Configure<ClientCredentialsOptions>(Configuration.GetSection(nameof(ClientCredentialsOptions)));
//...
}
//...
ProtectedResourceService.cs
//...
public class ProtectedResourceService : IProtectedResourceService
{
private readonly IHttpClientServiceFactory _requestServiceFactory;
private readonly IOptions<ClientCredentialsOptions> _identityServerOptions;
public ProtectedResourceService(IHttpClientServiceFactory requestServiceFactory, IOptions<ClientCredentialsOptions> identityServerOptions)
{
_requestServiceFactory = requestServiceFactory;
_identityServerOptions = identityServerOptions;
}
public async Task<YourObject> Get(){
_requestServiceFactory
.CreateHttpClientService()
.SetIdentityServerOptions(_identityServerOptions)
.GetAsync<YourObject>("https://url_that_returns_YourObject");
}
)
//...
.SetIdentityServerOptions<TOptions>(Action<TOptions>)
Setup IdentityServer options using a delegate:
//...
.SetIdentityServerOptions<PasswordOptions>( x => {
x.Address = "https://demo.identityserver.io/connect/token";
x.ClientId = "ClientId";
x.ClientSecret = "ClientSecret";
x.Scope = "Scope";
x.Username = "Username";
x.Password = "Password";
}
)
//...
More info on how to serialize request, deserialize response
Responses can always be deserialized to the type TResponseBody with GetAsync<TResponseBody>:
//...
.GetAsync<ResponsePoco>("https://url_that_returns_ResponsePoco_in_json");
//...
Using a complex type as a request body for POST, PUT and PATCH requests is also very easy. In the example that follows the type TRequestBody of the PostAsync<TRequestBody,TResponseBody> sets the type of the requestPoco object. This will be serialized using JsonConvert.SerializeObject(requestPoco, Formatting.None):
//...
.PostAsync<RequestP
Related Skills
node-connect
343.3kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
92.1kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
343.3kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
qqbot-media
343.3kQQBot 富媒体收发能力。使用 <qqmedia> 标签,系统根据文件扩展名自动识别类型(图片/语音/视频/文件)。
