C# - How to match a specific header in Wiremock.Net

Using Wiremock.Net you can set a requestmatcher to only match a request if it contains a specific header with a specific value, in this post I show you how using the .WithHeader() method.

Below I have made a simple example where I start Wiremock and mock requests with the path /weatherforecastbackend and with the header MyFantasticHeader to return OK and some JSON. It also requires the header to have the value MyFantasticValue:

var stubResponseSerialized = JsonConvert.SerializeObject(someObject); //not important what this JSON is.. just an example.
var server = WireMockServer.Start(58116);
server
    .Given(
        Request.Create()
            .WithPath("/weatherforecastbackend")
            .WithHeader("MyFantasticHeader", "MyFantasticValue") //important part
            .UsingGet()
    )
    .RespondWith(
        Response.Create()
            .WithStatusCode(200)
            .WithBody(stubResponseSerialized)
    );

We can test our newly mocked endpoint by running the following code:

var requestMessage = new HttpRequestMessage(HttpMethod.Get, 
   "http://localhost:58116/weatherforecastbackend");
requestMessage.Headers.Add("MyFantasticHeader", "MyFantasticValue");
var result = await _httpClient.SendAsync(requestMessage);

That is basically all there is to it. If you want to do something more delicate you can provide the WithHeader method with an IStringMatcher. This is perfect for mocking and below is an example of that using NSubstitute:

var stubResponseSerialized = JsonConvert.SerializeObject(someObject); //not important what this JSON is.. just an example.
var server = WireMockServer.Start(58116);         

var headerMatcher = Substitute.For<IStringMatcher>(); //important part
headerMatcher.IsMatch("MyFantasticValue").Returns(1); //important part

server
    .Given(
        Request.Create()
            .WithPath("/weatherforecastbackend")
            .WithHeader("MyFantasticHeader", headerMatcher) //important part
            .UsingGet()
    )
    .RespondWith(
        Response.Create()
            .WithStatusCode(200)
            .WithBody(stubResponseSerialized)
    );

Note: The IsMatch method of the IStringMatcher does not return a bool but a number between 0 and 1 based on how well it matches.

That is all there is to it, please let me know in the comments down below if you found this helpful! :)