Skip to content

DynamicRequestHeadersHandler

Troy Willmot edited this page Sep 25, 2016 · 1 revision

Dynamic Request Headers Handler

Summary

The DynamicRequestHeaderHandler adds headers to requests. While HttpClient already supports adding custom headers via the DefaultHeaders property, it requires the value to be fixed for the life of the client, or for the collection to be modified before each call which can be problematic in multi-threaded scenarios. The DynamicRequestHeaderHandler determines the value of the header at the time each request is made, eliminating these issues.

This can be useful for including values such as a currently logged on user (in systems where the user can change frequently), dates & times, unique request id's and so on.

Samples

// Create a dictionary containing the dynamic Headers
// Each dictionary entry has a key matching the header name in the request 
// and the value is a delegate or lambda expression that returns the 
// value for the header. The vaue must be returned as a string.

// In this sample 'TestHeader' is added will contain a unique GUID value
// on every request.
var dynamicHeaders = new Dictionary<string, Func<string>>();
dynamicHeaders.Add("TestHeader", () => System.Guid.NewGuid().ToString());

// Now create the handler using the list of dynamic headers, and a client
// using the handler.
var handler = new DynamicRequestHeaderHandler(dynamicHeaders, mockHandler);
var client = new HttpClient(handler);

// Make a request, which will autoamtically include the dynamic headers.
var result = await client.GetAsync("http://sometestsite.com/SomeEndPoint");

Clone this wiki locally