For people in need of a header but also additional data in their HttpContext, you can do so by initializing the context with features thanks to the second constructor of the DefaultHttpContext class:
1. Create a header dictionary with the headers you need:
var headers = new Dictionary<string, StringValues>
{
{ "myHeaderKey", "myHeaderValue" },
};
var headerDictionary = new HeaderDictionary(headers)
2. Create an HttpRequestFeature with the previously created header dictionary:
var requestFeature = new HttpRequestFeature()
{
Headers = headerDictionary,
};
3. Create a Feature collection containing the feature previously created :
var features = new FeatureCollection();
features.Set<IHttpRequestFeature>(requestFeature);
4. Initialize the DefaultHttpContext with the feature collection, and set it as the HttpContext of your controller:
var httpContext = new DefaultHttpContext(features);
var controller = new MyController();
controller.ControllerContext = new ControllerContext();
controller.ControllerContext.HttpContext = httpContext;
The controller's context will have the correct headers set, and you can still feed the context with more data as needed by setting additional HttpContext attributes to the featureCollection before instantiating the DefaultHttpContext (like feature.Set<IQueryFeature>(new QueryFeature(...))
for the query string for instance).
PS: For a more in-depth explanation on using features to mock (and unit testing in general) an HttpContext, see: https://weblogs.asp.net/ricardoperes/unit-testing-the-httpcontext-in-controllers