tiagodaraujo / HttpContextMoq

MIT License
34 stars 14 forks source link

Header names are case-sensitive #9

Closed xps closed 8 months ago

xps commented 1 year ago

Hi, and thanks for this great library.

In the ASP.NET Core runtime, getting the headers by key is case-insensitive. For example, this will be true:

Request.Headers["user-agent"] == Request.Headers["User-Agent"]

You can see here that the dictionary uses a StringComparer.OrdinalIgnoreCase: https://source.dot.net/#Microsoft.AspNetCore.Http/HeaderDictionary.cs,53

However, in HttpContextMoq, the following test fails:

[Fact]
public void Request_Headers_Should_Be_Case_Insensitive()
{
    // Act
    var context = new HttpContextMock().SetupRequestHeaders(new Dictionary<string, StringValues>() {
        { "header", "value" }
    });

    // Assert
    context.Request.Headers["Header"].Should().BeEquivalentTo("value");
}

This fails even if a StringComparer.OrdinalIgnoreCase is passed to the dictionary constructor:

[Fact]
public void Request_Headers_Should_Be_Case_Insensitive()
{
    // Act
    var context = new HttpContextMock().SetupRequestHeaders(new Dictionary<string, StringValues>(StringComparer.OrdinalIgnoreCase) {
        { "header", "value" }
    });

    // Assert
    context.Request.Headers["Header"].Should().BeEquivalentTo("value");
}

One way to fix this and make sure the mock always behave like the original would be to add the missing StringComparer.OrdinalIgnoreCase to the constructors:

public HeaderDictionaryFake()
{
    _dictionary = new Dictionary<string, StringValues>(StringComparer.OrdinalIgnoreCase);
}

public HeaderDictionaryFake(IDictionary<string, StringValues> dictionary)
{
    _dictionary = new Dictionary<string, StringValues>(dictionary, StringComparer.OrdinalIgnoreCase);
}

It seems like the best approach to me, but it is a breaking change. If you're happy with that, I can submit a PR. If not, let me know what you think would be a good fix.

Thanks

tiagodaraujo commented 8 months ago

Hi @xps

Sorry for the delay and thank you for your suggestion and interest in using the library.

I agree with you, not only the headers but also, the session, form, cookie, and form are case-insensitive.

You can find the fix on the latest version 1.6.0

https://github.com/tiagodaraujo/HttpContextMoq/commit/74fc2fb3c133fe111b48570f27c5fe6f2d9495b4

Thank You

xps commented 8 months ago

Hi @tiagodaraujo,

That's great, thank you. I tested the latest version and I can confirm the fix.

Closing this issue.