Click here to Skip to main content
14,732,945 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey there.

I am having a very interesting scenario, when core app adds something additional to my headers. I am inspecting all incoming requests and using the middleware to to inspect headers before processing the request:
public async Task Invoke(HttpContext httpContext)
    if (httpContext.Request.Headers.Keys.ToArray()[0] != "UserKey")
        throw new Exception("Wrong header order");

    await _next(httpContext);

I have also set this in startup.cs:
<pre>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    if (env.IsDevelopment())

    // do this before others


Though for some reason when I try to inspect the headers during the time request is in middleware I can see that some default headers been added for "Connection" and "Keep-Alive". And these were set on top (meaning they are first in the header collection).
I tried doing manual request with Fiddler like that:
GET http://localhost:49669/headers HTTP/1.1
Key_1: Value_1
Key_2: Value_2
Key_3: Value_3
Host: localhost:49669
Connection: Close

But still - when I inspect the headers I can see that Connection was set to "Keep-Alive" and the header ordering has been lost.
Any idea where to look?
Maybe there is some additional event I can attach to (without using the middleware)?


What I have tried:

Tried using middleware class but that did not quiet help.
Updated 7-Jun-18 5:45am

1 solution

That's nothing to do with ASP.NET; those headers are being sent the client.
The order in which header fields with differing field names are received is not significant. However, it is "good practice" to send general-header fields first, followed by request-header or response-header fields, and ending with the entity-header fields.

Most clients will put "general" headers - like Connection and Keep-Alive - before any other headers.

Relying on headers being sent in a specific order is extremely fragile, and will break almost immediately.

Instead, you should test whether the headers dictionary contains the expected header:
public async Task Invoke(HttpContext httpContext)
    if (!httpContext.Request.Headers.ContainsKey("UserKey"))
        throw new InvalidOperationException("Required header is missing.");

    await _next(httpContext);
MK-Gii 7-Jun-18 13:06pm
In my case it's pretty important. I will allow only users using specific agent, where headers are no reorganized, to access the site, this way preventing the bots and not authorized users from walking over my lawn. I know there are other ways of bot-protecting, but I just like this one.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900