Adsk.Platform.HttpClient 1.0.0

dotnet add package Adsk.Platform.HttpClient --version 1.0.0
                    
NuGet\Install-Package Adsk.Platform.HttpClient -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Adsk.Platform.HttpClient" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Adsk.Platform.HttpClient" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Adsk.Platform.HttpClient" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Adsk.Platform.HttpClient --version 1.0.0
                    
#r "nuget: Adsk.Platform.HttpClient, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Adsk.Platform.HttpClient@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Adsk.Platform.HttpClient&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Adsk.Platform.HttpClient&version=1.0.0
                    
Install as a Cake Tool

Autodesk.Common.HttpClientLibrary

⚠️ UNOFFICIAL PACKAGE ⚠️

A resilient HttpClient library designed to serve the Autodesk Platform Services (APS) Toolkit SDKs. This library provides a robust foundation for making HTTP requests with built-in error handling, rate limiting, query parameter management, and authentication support.

Overview

The Autodesk.Common.HttpClientLibrary is built on top of Microsoft Kiota's HttpClient foundation and extends it with custom middleware handlers specifically designed for Autodesk's API ecosystem. It provides a reliable, configurable HTTP client with enterprise-grade features.

Features

  • Resilient HTTP Client: Built-in retry logic and error handling
  • Rate Limiting: Configurable request rate limiting per endpoint
  • Error Handling: Automatic error response handling with detailed exception information
  • Query Parameter Management: Dynamic query parameter injection
  • Authentication Support: Bearer token authentication with flexible token providers
  • Dependency Injection: Full support for .NET dependency injection containers
  • Middleware Pipeline: Extensible middleware architecture

Installation

dotnet add package Adsk.Platform.HttpClient

Quick Start

Basic Usage

using Autodesk.Common.HttpClientLibrary;

// Create a basic HttpClient (rate limiting is disabled by default)
var httpClient = HttpClientFactory.Create();

// Create with rate limiting enabled
var rateLimitedClient = HttpClientFactory.Create((maxConcurrentRequests: 10, timeWindow: TimeSpan.FromMinutes(1)));

With Authentication

using Autodesk.Common.HttpClientLibrary;

// Define your token provider
Func<Task<string>> getAccessToken = async () => 
{
    // Your token acquisition logic here
    return await GetAccessTokenFromYourAuthProvider();
};

// Create authenticated adapter
var httpClient = HttpClientFactory.Create();
var adapter = HttpClientFactory.CreateAdapter(getAccessToken, httpClient);

Dependency Injection Setup

using Autodesk.Common.HttpClientLibrary;
using Microsoft.Extensions.DependencyInjection;

// In your Startup.cs or Program.cs
services.AddAdskToolkitHttpClient("MyHttpClient");

// Use in your services
public class MyService
{
    private readonly HttpClient _httpClient;
    
    public MyService(IHttpClientFactory httpClientFactory)
    {
        _httpClient = httpClientFactory.CreateClient("MyHttpClient");
    }
}

Core Components

HttpClientFactory

The main entry point for creating HttpClient instances with preconfigured middleware.

public static class HttpClientFactory
{
    // Create basic HttpClient
    public static HttpClient Create();
    
    // Create HttpClient with rate limiting
    public static HttpClient Create((int maxConcurrentRequests, TimeSpan timeWindow)? rateLimit);
    
    // Create HttpClient with custom options
    public static HttpClient Create(HttpMessageHandler? finalHandler = null, IRequestOption[]? optionsForHandlers = null);
    
    // Create authenticated request adapter
    public static HttpClientRequestAdapter CreateAdapter(Func<Task<string>> getAccessToken, HttpClient? httpClient);
}

Middleware Components

The HTTP pipeline includes both Kiota built-in handlers (provided by KiotaClientFactory.CreateDefaultHandlers()) and custom handlers added by this library.

Kiota Built-in Handlers

These handlers are inherited from the Microsoft Kiota HTTP library and are included automatically in every HttpClient created by HttpClientFactory.Create():

Handler Description Key options
UriReplacementHandler Replaces URI path segments at runtime (e.g., switching between API versions or environments). Disabled by default. isEnabled, replacementPairs (key/value pairs applied to the URI path)
RetryHandler Retries on 429, 503, and 504 with exponential backoff. Respects Retry-After headers. MaxRetry (default 3, max 10), Delay (default 3 s, max 180 s), RetriesTimeLimit, ShouldRetry delegate
RedirectHandler Follows 301/302 redirects. Scrubs Authorization/Cookie headers on cross-origin redirects. MaxRedirect (default 5, max 20), AllowRedirectOnSchemeChange, ShouldRedirect delegate
ParametersNameDecodingHandler Decodes query parameter names encoded per RFC 6570 (e.g., %24select$select). ParametersToDecode (characters to decode, defaults to ., -, ~, $, etc.)
UserAgentHandler Appends the Kiota product info to the User-Agent request header. Enabled (default true), ProductName, ProductVersion
HeadersInspectionHandler Allows callers to inspect request and response headers via the options object. InspectRequestHeaders, InspectResponseHeaders (both default false)
BodyInspectionHandler Allows callers to inspect request and response bodies via the options object. InspectRequestBody, InspectResponseBody (both default false)

Source: KiotaClientFactory.cs — all options can be passed via the optionsForHandlers parameter when calling HttpClientFactory.Create().

Custom Handlers

The following handlers are specific to this library and are appended after the Kiota defaults:

RateLimitingHandler

Implements per-endpoint rate limiting to prevent API quota exhaustion. Disabled by default — must be explicitly enabled via SetRateLimit().

Features:

  • Configurable maximum concurrent requests
  • Configurable time windows
  • Per-endpoint limiting (based on HTTP method and path)
  • Per-endpoint overrides with glob-style pattern matching (* wildcard)
  • Automatic request queuing and retry

Configuration:

var rateLimitOption = new RateLimitingHandlerOption();
rateLimitOption.SetRateLimit(maxConcurrentRequests: 5, timeWindow: TimeSpan.FromMinutes(1));

// Optionally set different limits for specific endpoints (exact match)
rateLimitOption.EndpointOverrides["POST|/api/expensive-operation"] = (2, TimeSpan.FromMinutes(1));

// Glob patterns with * wildcard are supported
rateLimitOption.EndpointOverrides["GET|/api/projects/*/items"] = (10, TimeSpan.FromMinutes(1));
rateLimitOption.EndpointOverrides["*|/api/slow-endpoint"] = (3, TimeSpan.FromMinutes(1));

var httpClient = HttpClientFactory.Create(null, new IRequestOption[] { rateLimitOption });

CustomErrorHandler

Provides centralized error handling for HTTP responses. The middleware itself never decides what is an error — the delegate does.

Features:

  • Delegate-driven: a Func<HttpContext, HandlerOutcome> receives the full request/response context and decides what to do (throw, return, log, etc.)
  • Default behaviour: throws ApiException for non-2xx responses, with the HttpContext attached in exception.Data["context"]
  • Non-throwing error signalling via HandlerOutcome(IsError: true) — response is returned to the caller, span is marked as error
  • Configurable success-status regex via DefaultCustomErrorHandler
  • Enable/disable per request via Enabled

Default (throws ApiException on non-2xx):

// No configuration needed — this is the default behaviour
var httpClient = HttpClientFactory.Create();

try
{
    var response = await httpClient.GetAsync("https://developer.api.autodesk.com/...");
}
catch (ApiException ex)
{
    var context = (HttpContext)ex.Data["context"];
    Console.WriteLine(context.ResponseContentAsString);
}

Custom success-status pattern (reuse default logic):

using System.Text.RegularExpressions;

// Accept 2xx and 404 as valid — do not throw on 404
var pattern = new Regex(@"^(2\d{2}|404)$");
var errorOption = new CustomErrorHandlerOption
{
    CustomErrorHandler = ctx =>
        CustomErrorHandlerOption.DefaultCustomErrorHandler(ctx, pattern)
};
var httpClient = HttpClientFactory.Create(null, [errorOption]);

Fully custom delegate — non-throwing error signalling:

var errorOption = new CustomErrorHandlerOption
{
    CustomErrorHandler = ctx =>
    {
        if ((int)ctx.StatusCode is >= 200 and < 300)
            return HandlerOutcome.Ok;

        if ((int)ctx.StatusCode == 429)
            // Return response to caller, mark the span as error — do not throw
            return new HandlerOutcome(IsError: true, Description: "Rate limited");

        throw new ApiException($"HTTP {(int)ctx.StatusCode}");
    }
};

QueryParameterHandler

Dynamically adds query parameters to HTTP requests.

Features:

  • Runtime query parameter injection
  • Preserves existing query parameters
  • Flexible parameter management

Configuration:

var queryOption = new QueryParameterHandlerOption();
queryOption.QueryParameters.Add("api-version", "1.0");
queryOption.QueryParameters.Add("region", "us-east-1");

var httpClient = HttpClientFactory.Create(null, new IRequestOption[] { queryOption });

Advanced Configuration

Custom Middleware Pipeline

// Get default handler types
var handlerTypes = HttpClientFactory.GetDefaultHandlerActivatableTypes();

// Create custom configuration
var customOptions = new IRequestOption[]
{
    new RateLimitingHandlerOption(),   // Rate limiting disabled by default — call SetRateLimit() to enable
    new CustomErrorHandlerOption(),    // Throws ApiException on non-2xx by default
    new QueryParameterHandlerOption()
};

var httpClient = HttpClientFactory.Create(finalHandler: null, optionsForHandlers: customOptions);

Per-Request Options

You can override default options on a per-request basis:

var request = new HttpRequestMessage(HttpMethod.Get, "https://api.example.com/data");

// Add request-specific rate limiting
var requestRateLimit = new RateLimitingHandlerOption();
requestRateLimit.SetRateLimit(1, TimeSpan.FromSeconds(5));
request.Options.Add(requestRateLimit.GetType().Name, requestRateLimit);

var response = await httpClient.SendAsync(request);

Best Practices

1. Use Dependency Injection

Register the HttpClient in your DI container for better testability and lifecycle management:

services.AddAdskToolkitHttpClient("ApsHttpClient");

2. Configure Appropriate Rate Limits

Set rate limits based on your API's documented limits:

// For APIs with 100 requests per minute limit
var httpClient = HttpClientFactory.Create((maxConcurrentRequests: 100, timeWindow: TimeSpan.FromMinutes(1)));

3. Implement Proper Token Management

Use a robust token provider that handles token refresh:

Func<Task<string>> getAccessToken = async () =>
{
    if (IsTokenExpired())
    {
        await RefreshToken();
    }
    return CurrentAccessToken;
};

4. Handle Errors Gracefully

While the ErrorHandler provides automatic exception throwing, implement proper error handling in your application:

try
{
    var response = await httpClient.GetAsync("https://api.example.com/data");
    // Process response
}
catch (HttpRequestException ex) when (ex.Data.Contains("context"))
{
    var httpResponse = (HttpResponseMessage)ex.Data["context"];
    // Handle specific error cases based on status code
}

Thread Safety

All components in this library are thread-safe and can be used in concurrent scenarios. The HttpClient instances created by the factory are safe to use across multiple threads.

Performance Considerations

  • HttpClient Reuse: Reuse HttpClient instances rather than creating new ones for each request
  • Rate Limiting: Configure appropriate rate limits to balance performance with API compliance
  • Connection Pooling: The underlying HttpClient uses connection pooling for optimal performance

Dependencies

  • .NET 8.0: Target framework
  • Microsoft.Extensions.Http: HTTP client factory and DI integration
  • Microsoft.Kiota.Http.HttpClientLibrary: Base HTTP client library with Kiota integration

Examples

Complete Example with Authentication and Rate Limiting

using Autodesk.Common.HttpClientLibrary;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);

// Register HttpClient
builder.Services.AddAdskToolkitHttpClient("ApsClient");

// Register your token provider
builder.Services.AddScoped<ITokenProvider, YourTokenProvider>();

var host = builder.Build();

// Use the client
var httpClientFactory = host.Services.GetRequiredService<IHttpClientFactory>();
var tokenProvider = host.Services.GetRequiredService<ITokenProvider>();

var httpClient = httpClientFactory.CreateClient("ApsClient");
var adapter = HttpClientFactory.CreateAdapter(
    () => tokenProvider.GetTokenAsync(), 
    httpClient
);

// Use adapter with your SDK clients
var dataManagementClient = new DataManagementClient(adapter);

Troubleshooting

Common Issues

  1. Rate Limiting Too Aggressive: Adjust rate limit parameters based on actual API limits
  2. Authentication Failures: Ensure your token provider returns valid, non-expired tokens
  3. Timeout Issues: Configure appropriate timeout values for your use case

Debugging

Enable detailed logging to troubleshoot issues:

services.AddLogging(builder => builder.AddConsole().SetMinimumLevel(LogLevel.Debug));

License

This library is licensed under the MIT License. See LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (19)

Showing the top 5 NuGet packages that depend on Adsk.Platform.HttpClient:

Package Downloads
Adsk.Platform.DataManagement

Autodesk Platform: Data Management Service SDK and tools

Adsk.Platform.Authentication

Autodesk Platform: Authentication Service SDK and tools

Adsk.Platform.ModelDerivative

Autodesk Platform: Model Derivative Service SDK and tools

Adsk.Platform.ACC.AccountAdmin

Autodesk Platform: ACC Account service SDK and tools

Adsk.Platform.ACC.CostManagement

Autodesk Platform: ACC Cost Service SDK and tools

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 97 6/8/2026
0.3.17 305 4/7/2026
0.3.16 283 3/31/2026
0.3.15 266 3/30/2026
0.3.14 244 3/23/2026
0.3.13 253 3/19/2026
0.3.12 252 3/19/2026
0.3.11 266 3/19/2026
0.3.10 249 3/18/2026
0.3.9 255 3/17/2026
0.3.8 252 3/17/2026
0.3.7 243 3/12/2026
0.3.6 266 3/10/2026
0.3.5 223 3/8/2026
0.3.4 213 3/8/2026
0.3.3 209 3/6/2026
0.3.2 221 3/5/2026
0.3.1 222 3/2/2026
0.3.0 194 3/2/2026
0.2.9 222 2/11/2026
Loading failed