![]() |
VOOZH | about |
dotnet add package CG.Infrastructure.Http --version 3.10.8
NuGet\Install-Package CG.Infrastructure.Http -Version 3.10.8
<PackageReference Include="CG.Infrastructure.Http" Version="3.10.8" />
<PackageVersion Include="CG.Infrastructure.Http" Version="3.10.8" />Directory.Packages.props
<PackageReference Include="CG.Infrastructure.Http" />Project file
paket add CG.Infrastructure.Http --version 3.10.8
#r "nuget: CG.Infrastructure.Http, 3.10.8"
#:package CG.Infrastructure.Http@3.10.8
#addin nuget:?package=CG.Infrastructure.Http&version=3.10.8Install as a Cake Addin
#tool nuget:?package=CG.Infrastructure.Http&version=3.10.8Install as a Cake Tool
A comprehensive HTTP client library for .NET applications that provides robust HTTP operations, authentication support, proxy configuration, and response handling with multiple client types and security features.
dotnet add package CG.Infrastructure.Http
using Infrastructure.Http.Extensions;
var builder = WebApplication.CreateBuilder(args);
// Register HTTP services
builder.Services.RegisterInfraHttpServices(builder.Configuration);
public class MyController : ControllerBase
{
private readonly IHttpService _httpService;
public MyController(IHttpService httpService)
{
_httpService = httpService;
}
public async Task<IActionResult> GetData()
{
var response = await _httpService.Get("api/data");
var data = await _httpService.GetResponseAsEntity<MyData>(response);
return Ok(data);
}
}
{
"ProxyOptions": {
"UseProxy": false,
"ProxyHost": "proxy.company.com",
"ProxyPort": 8080
},
"IssuerOptions": {
"Authority": "https://identity.example.com",
"Audience": "my-api"
},
"CustomHeaders": {
"Headers": {
"x-gg-bot-access": "{{ENV:GG_BOT_ACCESS_TOKEN}}",
"Accept": "application/json"
}
}
}
Comprehensive HTTP service interface with authentication and response handling:
public interface IHttpService : IService
{
// HTTP Operations
Task<HttpResponseMessage?> Get(string? requestUri, TokenResponse? token = null, string? baseUrl = null, HttpClientEnum client = HttpClientEnum.Basic);
Task<HttpResponseMessage?> Post<TEntity>(string? requestUri, TEntity? data, TokenResponse? token = null, string? baseUrl = null, HttpClientEnum client = HttpClientEnum.Basic);
Task<HttpResponseMessage?> Put<TEntity>(string? requestUri, TEntity? data, TokenResponse? token = null, string? baseUrl = null, HttpClientEnum client = HttpClientEnum.Basic);
Task<HttpResponseMessage?> Delete(string? requestUri, Guid? id, TokenResponse? token = null, string? baseUrl = null, HttpClientEnum client = HttpClientEnum.Basic);
// Response Handling
Task<string> GetResponseAsString(HttpResponseMessage response);
Task<string[]> GetResponseAsStringArray(HttpResponseMessage response);
Task<TEntity?> GetResponseAsEntity<TEntity>(HttpResponseMessage response);
// Authentication
Task<DiscoveryDocumentResponse?> GetDiscoveryDocument(string? requestUri, HttpClientEnum client = HttpClientEnum.Basic);
Task<TokenResponse?> RequestClientToken(string? requestUri, ClientCredentialsTokenRequest request, HttpClientEnum client = HttpClientEnum.Basic);
Task<TokenResponse?> RequestPasswordToken(string? requestUri, PasswordTokenRequest request, HttpClientEnum client = HttpClientEnum.Basic);
Task<UserInfoResponse?> GetUserInfo(string? requestUri, UserInfoRequest request, HttpClientEnum client = HttpClientEnum.Basic);
// Testing and Utilities
Task<bool> Test(string? requestUri, string? format = null, HttpClientEnum client = HttpClientEnum.Basic);
Task TestWithToken(TokenResponse? token, string? requestUri, string? format = null, HttpClientEnum client = HttpClientEnum.Basic);
Task TestApiClientLinks(List<TestLink>? testLinks);
bool PingHost(string? nameOrAddress);
}
// GET request
var response = await _httpService.Get("api/users");
// POST request with entity
var user = new User { Name = "John", Email = "john@example.com" };
var response = await _httpService.Post("api/users", user);
// PUT request with entity
var updatedUser = new User { Id = 1, Name = "John Updated", Email = "john.updated@example.com" };
var response = await _httpService.Put("api/users/1", updatedUser);
// DELETE request
var response = await _httpService.Delete("api/users", Guid.Parse("12345678-1234-1234-1234-123456789012"));
// GET request with custom headers (authenticated client)
var response = await _httpService.Get("api/protected", client: HttpClientEnum.Authenticated);
// POST request with custom headers
var response = await _httpService.Post("api/secure", data, client: HttpClientEnum.Authenticated);
// All HTTP methods support custom headers via HttpClientEnum.Authenticated
// Get response as string
var response = await _httpService.Get("api/data");
var content = await _httpService.GetResponseAsString(response);
// Get response as string array
var response = await _httpService.Get("api/items");
var items = await _httpService.GetResponseAsStringArray(response);
// Get response as typed entity
var response = await _httpService.Get("api/users");
var users = await _httpService.GetResponseAsEntity<List<User>>(response);
// Create client credentials request
var request = _httpService.GetClientCredentialsToken(
"https://identity.example.com/connect/token",
"client-id",
"client-secret",
"api-scope"
);
// Request token
var token = await _httpService.RequestClientToken(
"https://identity.example.com/connect/token",
request
);
// Use token for authenticated requests
var response = await _httpService.Get("api/protected", token);
// Create password token request
var securePassword = new SecureString();
foreach (char c in "password123") securePassword.AppendChar(c);
var request = _httpService.GetClientPasswordToken(
"https://identity.example.com/connect/token",
"client-id",
"client-secret",
"api-scope",
"username",
securePassword
);
// Request token
var token = await _httpService.RequestPasswordToken(
"https://identity.example.com/connect/token",
request
);
// Get user info request
var userInfoRequest = _httpService.GetUserInfoRequest(
"https://identity.example.com/connect/userinfo",
token
);
// Retrieve user information
var userInfo = await _httpService.GetUserInfo(
"https://identity.example.com/connect/userinfo",
userInfoRequest
);
// Get OpenID Connect discovery document
var discovery = await _httpService.GetDiscoveryDocument(
"https://identity.example.com"
);
if (discovery != null)
{
var tokenEndpoint = discovery.TokenEndpoint;
var userInfoEndpoint = discovery.UserInfoEndpoint;
}
public enum HttpClientEnum
{
Basic = 1, // Standard HTTP client
Token = 2, // Token-based authentication client
Handler = 3, // Custom message handler client
Authenticated = 4 // Client with custom headers (e.g., API keys, custom Accept)
}
// Basic client (default)
var response = await _httpService.Get("api/data", client: HttpClientEnum.Basic);
// Token-based client
var response = await _httpService.Get("api/protected", token, client: HttpClientEnum.Token);
// Custom handler client
var response = await _httpService.Get("api/data", client: HttpClientEnum.Handler);
// Authenticated client with custom headers
var response = await _httpService.Get("api/secure", client: HttpClientEnum.Authenticated);
When using HttpClientEnum.Authenticated:
Accept header takes precedence)public class ProxyOptions
{
public string? Url { get; set; } // Proxy URL
public bool UseProxy { get; set; } = false; // Enable/disable proxy
public string? ProxyHost { get; set; } // Proxy hostname
public int ProxyPort { get; set; } // Proxy port number
}
public class CustomHeaderOptions
{
public Dictionary<string, string> Headers { get; set; } = new();
}
{
"ProxyOptions": {
"UseProxy": true,
"ProxyHost": "proxy.company.com",
"ProxyPort": 8080
},
"CustomHeaders": {
"Headers": {
"x-api-key": "{{ENV:API_KEY}}",
"x-gg-bot-access": "{{ENV:GG_BOT_ACCESS_TOKEN}}",
"Accept": "application/json",
"User-Agent": "MyApp/1.0"
}
}
}
Custom headers support environment variable substitution using the {{ENV:VARIABLE_NAME}} syntax:
# Set environment variables
export API_KEY="your-api-key-here"
export GG_BOT_ACCESS_TOKEN="your-bot-token-here"
# Or in Windows PowerShell
$env:API_KEY="your-api-key-here"
$env:GG_BOT_ACCESS_TOKEN="your-bot-token-here"
public class CustomHttpMessageHandler : HttpMessageHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
// Custom logic before request
request.Headers.Add("X-Custom-Header", "CustomValue");
// Send request
var response = await base.SendAsync(request, cancellationToken);
// Custom logic after response
return response;
}
}
// Use custom handler
var handler = new CustomHttpMessageHandler();
var httpService = new HttpService(logger, proxyOptions, issuerOptions,
serializationService, substringService, secureStringService, handler);
// Use base URL for all requests
var response = await _httpService.Get("users", baseUrl: "https://api.example.com");
// Results in: https://api.example.com/users
// Combine base URL with specific endpoint
var response = await _httpService.Post("users", user, baseUrl: "https://api.example.com");
// Results in: https://api.example.com/users
// Test endpoint availability
var isAvailable = await _httpService.Test("https://api.example.com/health");
// Test with specific format
var isAvailable = await _httpService.Test("https://api.example.com/health", "json");
// Test with authentication token
await _httpService.TestWithToken(token, "https://api.example.com/protected");
// Test multiple API client links
var testLinks = new List<TestLink>
{
new TestLink
{
TokenEndpoint = "https://identity.example.com/connect/token",
ClientId = "client-id",
ClientSecret = "client-secret",
ClientScope = "api-scope",
Links = new Dictionary<string, string?>
{
{ "Users", "https://api.example.com/users" },
{ "Orders", "https://api.example.com/orders" }
}
}
};
await _httpService.TestApiClientLinks(testLinks);
// Ping host to check connectivity
var isReachable = _httpService.PingHost("api.example.com");
var isReachable = _httpService.PingHost("192.168.1.1");
public static class ServiceCollectionExtensions
{
public static IServiceCollection RegisterInfraHttpServices(
this IServiceCollection services,
IConfiguration configuration)
{
services.RegisterProxyOptions(configuration);
services.RegisterCustomHeaderOptions(configuration);
// Register HttpClient as singleton with default headers
services.AddHttpClient<HttpService>(client =>
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
});
return services;
}
}
services.AddSingleton<ProxyOptions>(provider =>
{
var configuration = provider.GetRequiredService<IConfiguration>();
var proxyOptions = new ProxyOptions();
configuration.GetSection("ProxyOptions").Bind(proxyOptions);
return proxyOptions;
});
services.AddHttpClient<HttpService>();
services.AddScoped<IHttpService, HttpService>();
var response = await _httpService.Get("api/data");
if (response != null && response.IsSuccessStatusCode)
{
var data = await _httpService.GetResponseAsEntity<MyData>(response);
return Ok(data);
}
else
{
var errorContent = response != null
? await _httpService.GetResponseAsString(response)
: "No response received";
return BadRequest($"Request failed: {errorContent}");
}
try
{
var response = await _httpService.Get("api/data");
var data = await _httpService.GetResponseAsEntity<MyData>(response);
return Ok(data);
}
catch (HttpRequestException ex)
{
logger.LogError(ex, "HTTP request failed");
return StatusCode(500, "External service unavailable");
}
catch (Exception ex)
{
logger.LogError(ex, "Unexpected error");
return StatusCode(500, "Internal server error");
}
Enable detailed logging for troubleshooting:
// In appsettings.json
{
"Logging": {
"LogLevel": {
"Infrastructure.Http": "Debug"
}
}
}
This project is licensed under the MIT License - see the file for details.
For support and questions:
CG.Infrastructure.Http - Robust HTTP operations for modern .NET applications.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 net10.0 is compatible. net10.0-android net10.0-android was computed. net10.0-browser net10.0-browser was computed. net10.0-ios net10.0-ios was computed. net10.0-maccatalyst net10.0-maccatalyst was computed. net10.0-macos net10.0-macos was computed. net10.0-tvos net10.0-tvos was computed. net10.0-windows net10.0-windows was computed. |
Showing the top 1 NuGet packages that depend on CG.Infrastructure.Http:
| Package | Downloads |
|---|---|
|
CG.Infrastructure.Responses
Infra Responses library with shared services |
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 3.10.8 | 131 | 4/1/2026 |
| 3.10.7 | 207 | 8/16/2025 |
| 3.10.6 | 245 | 8/15/2025 |
| 3.10.5 | 251 | 8/10/2025 |
| 3.10.4 | 267 | 7/2/2025 |
| 3.10.3 | 259 | 6/17/2025 |
| 3.10.2 | 261 | 6/16/2025 |
| 3.10.1 | 405 | 6/11/2025 |
| 3.10.0 | 420 | 6/11/2025 |
| 3.9.0 | 222 | 12/10/2024 |
| 3.0.2 | 276 | 8/13/2024 |
| 3.0.1 | 269 | 8/12/2024 |
| 3.0.0 | 268 | 3/26/2024 |
| 2.0.1 | 405 | 6/2/2023 |
| 2.0.0 | 268 | 6/2/2023 |
| 1.0.2 | 624 | 6/17/2022 |
| 1.0.1 | 530 | 6/17/2022 |
| 1.0.0 | 642 | 5/27/2022 |