Http.Client.Options 7.2.0

There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package Http.Client.Options --version 7.2.0
NuGet\Install-Package Http.Client.Options -Version 7.2.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="Http.Client.Options" Version="7.2.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Http.Client.Options --version 7.2.0
#r "nuget: Http.Client.Options, 7.2.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.
// Install Http.Client.Options as a Cake Addin
#addin nuget:?package=Http.Client.Options&version=7.2.0

// Install Http.Client.Options as a Cake Tool
#tool nuget:?package=Http.Client.Options&version=7.2.0

Purpurse

Simplified usage of http client factory using Options pattern

Configuration options

All configuration are disabled by default

Connection

Http client base url properties

option value
server The domain name of the base url
port The port part of the base url
schema The schema part of the base url (http/ https)
timeout Connection timeout, will be set as http client timeout

 serviceCollection.AddHttpClientOptions(options =>
            {
                options.ServiceName = "jsonplaceholder";
                options.ConnectionOptions.Server = "jsonplaceholder.typicode.com";
                options.ConnectionOptions.Schema = "http";
                options.ConnectionOptions.Port = 80;
                options.ConnectionOptions.Timeout = Timeout; 
            });

Http Client Handler

The http client heandler properties

option value
MaxConnection The maximum number of concurrent connections (per server endpoint)
HandlerLifeTimeMinutes The length of time that a HttpMessageHandler instance can be reused

  serviceCollection.AddHttpClientOptions(options =>
            {
                options.ServiceName = "my-service"; 
                options.HttpClientHandlerOptions.MaxConnection = 1;
                options.HttpClientHandlerOptions.HandlerLifeTimeMinutes = 10;
            });

Polly Options

All policies are disabled by default

Bulkhead


  
            serviceCollection.AddHttpClientOptions(options =>
            {
                options.ServiceName = "service";

                options.PollyOptions.Bulkhead.Enabled = true;
                options.PollyOptions.Bulkhead.MaxParallelization = 100;
                options.PollyOptions.Bulkhead.MaxQueuingActions = 10000;


            });

Retry


  
            serviceCollection.AddHttpClientOptions(options =>
            {
                options.ServiceName = "service";

                options.PollyOptions.Retry.Enabled = true;
                options.PollyOptions.Retry.Count = 5;
                options.PollyOptions.Retry.BackoffPower = 3;
                options.PollyOptions.Retry.MaxJitter = 100;


            });

CircuitBreaker


  
            serviceCollection.AddHttpClientOptions(options =>
            {
                options.ServiceName = "service";

                options.PollyOptions.CircuitBreaker.Enabled = true;
                options.PollyOptions.CircuitBreaker.FailureThreshold = 0.7;
                options.PollyOptions.CircuitBreaker.MinimumThroughput = 20;
                options.PollyOptions.CircuitBreaker.SamplingDuration = 1000;



            });

Timeout


  
            serviceCollection.AddHttpClientOptions(options =>
            {
                options.ServiceName = "service";

                options.PollyOptions.Timeout.Enabled = true;
                options.PollyOptions.Timeout.TimeoutMS = 1000; 
            });

Open Telemetry

Use Open Telemetry and Http Instrumentation to trace the requests

Configure Open Telemetry builder

Tracing support request details, response, timing, and config, see more on how to customize open telemetry here

  serviceCollection.AddHttpOptionsTelemetry(optionsBuilder =>
               {
                   optionsBuilder.ConfigureOpenTelemetryBuilder(builder => builder.AddConsoleExporter());
               }
           ); 
Activity details example
Activity.Id:          00-057d78264f60ab804d6673a9c6d66fe9-5d99a746899f034a-01
Activity.DisplayName: http-options-activity
Activity.Kind:        Client
Activity.StartTime:   2022-04-25T21:13:18.7215742Z
Activity.Duration:    00:00:00.2143088
Activity.TagObjects:
    config.server: 127.0.0.1
    config.port: 64578
    config.schema: http
    config.name: service
    config.timeout: -1
    config.handler.maxConnection: 100
    config.handler.lifeTimeMinutes: 10
    correlation.id: a5262536662549b28e23a1c6ffae1dc9
    timestamp: 7276724051916
    http.method: GET
    http.url: http://127.0.0.1:64578/delay/200ms
    http.scheme: http
    http.target: 127.0.0.1
    http.route: /delay/200ms
    host.port: 64578
    http.status_code: 200
    time.start: 25/04/2022 21:13:18
    time.end: 25/04/2022 21:13:18
    time.duration: 00:00:00.2143088
    time.http.start: 25/04/2022 21:13:18
    time.http.end: 25/04/2022 21:13:18
    time.http.duration: 00:00:00.2141251
    time.delta.start.ms: 0.0156
    time.delta.end.ms: 0.1681
    time.delta.ms: 0.1837
    http.host: 127.0.0.1:64578
    otel.status_code: UNSET
Resource associated with Activity:
    service.name: http-options-service
    service.instance.id: 6f61406e-5267-43be-9a11-75b57173b15c

Customize tracing tags

Customize the tags by simply set the tag to any string

 serviceCollection.AddHttpOptionsTelemetry(optionsBuilder =>
                {
                    optionsBuilder.ConfigureTags(tagsOptions =>
                    {
                        tagsOptions.Config.Name = "name";
                        tagsOptions.Config.Port = "port";
                        tagsOptions.Config.Schema = "schema";
                        tagsOptions.Config.MaxConnection = "maxConnection";
                        tagsOptions.Request.Schema = "r.schema";
                        tagsOptions.Request.RequestLength = "size";
                        tagsOptions.Request.RequestPath = "path";
                        tagsOptions.Request.Host = "host";
                    });

                    optionsBuilder.ConfigureBuilder(builder => builder.AddConsoleExporter());
                }
            );
Activity tags example

Activity.TagObjects:
    config.server: 127.0.0.1
    port: 54347
    schema: http
    name: service
    config.timeout: -1
    maxConnection: 100
    r.schema: http
    host: 127.0.0.1
    path: /delay/200ms


 #... other tags as usual
  

Customize Enrichment

We are using Http Instrumentation to add tags about the request details, plus to additional tags provided by this library, but you can easily add any tag you want on request, response, or error events.

optionsBuilder.ConfigureEnrichment(enrichmentOptions =>
                        {
                            enrichmentOptions.OnRequest((activity, message) =>
                            {
                                activity.Tags["auth-custom-tag"] = message.AuthenticationLevel;
                            });


                            enrichmentOptions.OnResponse((activity, message) =>
                            {
                                activity.Tags["response.cookies.count"] = message.Cookies.Count;
                            });
                            
                            enrichmentOptions.OnError((activity, message) =>
                            {
                                activity.Tags["error.source"] = message.Source;
                            });
                        }
                    );

Customize Processor

While enrichment is called via http events, processor wil be called just as activity is starting and after all events are done, before sending the activity to the exporter.

Open Telemetry Processor

To add any open telemetry processor), simply configure telemetry with the processor.

  
  optionsBuilder.ConfigureOpenTelemetryBuilder(builder => builder.AddProcessor(new MyProcessor()));
  
Add action as processor

Allowing simple actions to start and end of activities as actions

   optionsBuilder.ConfigureProcessor(builder =>
                    {

                        builder
                            .OnActivityStart(activityContext =>
                            {
                                activityContext.Activity.SetTag("just-marker", "my-cool-service-did-it") ;

                            });
                        
                        builder
                            .OnActivityEnd(activityContext =>
                            {
                                activityContext.Activity.SetTag("is-long-request",  activityContext.Activity.Duration > TimeSpan.FromHours(1)) ;


                            });
                    });
Use activity properties to add data to be carried along the request .
  optionsBuilder.ConfigureProcessor(builder =>
                    {
                        builder
                            .OnActivityStart(activityContext =>
                            {
                                var counter = Counters.StartNewActivity(activityContext.ClientOptions.ServiceName);
                                activityContext.Activity.SetCustomProperty("request-counter", counter);
                            });

                        builder
                            .OnActivityEnd(activityContext =>
                            {
                                var counter =
                                    activityContext.Activity.GetCustomProperty("request-counter") as RequestCounter;
                                activityContext.Tags["request-counts"] = counter?.RequestEnd();

                            });
                    });

Customize Exporter

Open Telemetry Exporter

To add any Open Telemetry Exporter), simply configure the telemetry with the exporter.

   serviceCollection.AddHttpOptionsTelemetry(optionsBuilder =>
                {
                    optionsBuilder.ConfigureOpenTelemetryBuilder(builder => builder.AddConsoleExporter());
                }
            ); 

If you don't need a special open telemetry exporter, you can add any simple export action to be happened in export.

  serviceCollection.AddHttpOptionsTelemetry(optionsBuilder =>
                {
                    optionsBuilder.ConfigureExportAction(activity => _activities.Add(activity));
                }

Note that export actions will be called after all processing are done, don't change the activity at that point

Customize Activity Settings

     optionsBuilder.ConfigureTracing(options =>
                    {
                        options.Activity.Source = new ActivitySource("my-source");
                        options.Activity.ActivityName = "http-clint-activity";
                        options.Activity.ActivityService = "order-service";
                    });

Binding Options

Bind http Client by type

       serviceCollection.AddHttpClientOptions<ServiceClient>(options =>
            {
                options.ServiceName = "service";
             
                options.TelemetryOptions.Counter = true;
                options.TelemetryOptions.Timing = true;
  
            });
            

Usage of named client

  var factory = serviceProvider.GetRequiredService<IHttpClientFactory>();
  var client = factory.CreateClient("service");
  await client.GetAsync("todos/1");
   

Usage of typed client

class ServiceClient
       {
           private readonly HttpClient _httpClient;

           public ServiceClient(HttpClient httpClient)
           {
               _httpClient = httpClient;
           }

           public Task<HttpResponseMessage> Get()
           {
               return _httpClient.GetAsync("todos/1");
           }
       }
Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  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. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
8.0.0-beta.63 87 4/12/2023
8.0.0-beta.62 84 4/12/2023
8.0.0-beta.61 69 4/12/2023
8.0.0-beta.60 74 4/12/2023
8.0.0-beta.57 75 4/12/2023
8.0.0-beta.20 73 4/13/2023
8.0.0-beta.18 75 4/13/2023
8.0.0-beta.17 72 4/13/2023
8.0.0-beta.10 71 4/12/2023
8.0.0-beta.9 73 4/12/2023
8.0.0-beta.1 82 3/13/2023
8.0.0-alpha.10 69 4/13/2023
7.2.3-alpha 114 11/4/2022
7.2.2-alpha 98 11/3/2022
7.2.1-alpha 102 11/3/2022
7.2.0 19,096 4/27/2022
7.2.0-alpha 93 11/3/2022
7.1.0 124 4/25/2022
7.0.1 125 4/25/2022
6.0.1 13,704 2/21/2022
6.0.0.4 4,874 1/3/2022
6.0.0.3 280 1/3/2022
6.0.0.2 274 1/3/2022
6.0.0.1 10,611 11/10/2021
5.0.6 319 11/10/2021
5.0.0.2 309 11/10/2021
5.0.0.1 330 11/10/2021
5.0.0.1-preview 228 11/10/2021