Skip to content

Commit

Permalink
Merge pull request #4 from stevejgordon/ResponseHeaderBug
Browse files Browse the repository at this point in the history
Check if response header exists before trying to add it
  • Loading branch information
stevejgordon authored Oct 31, 2017
2 parents 015ace9 + 791583a commit 442744a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
14 changes: 6 additions & 8 deletions src/CorrelationId/CorrelationIdMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,8 @@ public class CorrelationIdMiddleware
/// <param name="options">The configuration options.</param>
public CorrelationIdMiddleware(RequestDelegate next, IOptions<CorrelationIdOptions> options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}

_next = next ?? throw new ArgumentNullException(nameof(next));

_options = options.Value;
_options = options?.Value ?? throw new ArgumentNullException(nameof(options));
}

/// <summary>
Expand All @@ -45,7 +39,11 @@ public Task Invoke(HttpContext context)
// apply the correlation ID to the response header for client side tracking
context.Response.OnStarting(() =>
{
context.Response.Headers.Add(_options.Header, new[] { context.TraceIdentifier });
if (!context.Response.Headers.ContainsKey(_options.Header))
{
context.Response.Headers.Add(_options.Header, new[] { context.TraceIdentifier });
}

return Task.CompletedTask;
});
}
Expand Down
20 changes: 19 additions & 1 deletion test/CorrelationId.Tests/CorrelationIdMiddlewareTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using System.Collections.Generic;
Expand Down Expand Up @@ -26,6 +27,23 @@ public async Task ReturnsCorrelationIdInResponseHeader_WhenOptionSetToTrue()
Assert.NotNull(header);
}

[Fact]
public async Task DoesNotThrowException_WhenOptionSetToTrue_IfHeaderIsAlreadySet()
{
var builder = new WebHostBuilder()
.Configure(app =>
{
app.UseCorrelationId();
app.UseCorrelationId(); // header will already be set on this second use of the middleware
});

var server = new TestServer(builder);

await server.CreateClient().GetAsync("");

// Note: This test will only fail if the middleware is causing an exception by trying to set a response header which already exists.
}

[Fact]
public async Task DoesNotReturnCorrelationIdInResponseHeader_WhenOptionSetToFalse()
{
Expand All @@ -38,7 +56,7 @@ public async Task DoesNotReturnCorrelationIdInResponseHeader_WhenOptionSetToFals

var response = await server.CreateClient().GetAsync("");

var headerExists = response.Headers.TryGetValues(options.Header, out IEnumerable<string> headerValue);
var headerExists = response.Headers.TryGetValues(options.Header, out IEnumerable<string> _);

Assert.False(headerExists);
}
Expand Down

0 comments on commit 442744a

Please sign in to comment.