I have a legacy project which uses .NET Framework 4.5.2 and NancyModule. When I get the result of a GET-request, then the Headers have the following order:
Key | Value |
---|---|
Content-Length | 206 |
Content-Type | application/json; charset=utf-8 |
Vary | Accept |
Server | Microsoft-HTTPAPI/2.0 |
Link | </Servicename.xml>; rel="application/xml" |
x-powered-by | ... |
Date | Tue, 31 Jan 2023 13:25:07 GMT |
I transfer this project to .net 6 and Microsoft.AspNetCore.Mvc. When I get the result of a GET-request, then the keys of the Headers are arranged alphabetically.
This leads me to the following question: Is it possible to change the order of the headers?
I tried to remove and add several values of the dictionary in HttpContext.Response.Headers but it has no entries. When I added a custom header then it was also in alphabetical order.
If you are using Kestrel (the default web server in ASP.NET Core) you might want to remove the Server
header in order to try to have the Date
header last.
But that would be very fragile, you can't really control the order of the headers, see the source code of how it's done!
For simple HTTP responses that don't set any special headers, this might work and you might end up with something like that. Note the many conditionals used in the previous sentences. 😉
HTTP/1.1 200 OK
Content-Length: 4536
Content-Type: text/plain
Date: Tue, 31 Jan 2023 14:58:31 GMT
And here's how to disable the Server
header for Kestrel:
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(serverOptions => serverOptions.AddServerHeader = false);
If you need to use HTTP.sys instead of Kestrel then you'll be out of luck since the Content-Length
header is added after the Date
header and there's nothing you can do about it.
HTTP/1.1 200 OK
Content-Type: text/plain
Server: Microsoft-HTTPAPI/2.0
Date: Tue, 31 Jan 2023 15:11:23 GMT
Content-Length: 4536