Home > database >  Is it possible to change the order of the Headers in a HttpWebResponseMessage using the ApiControlle
Is it possible to change the order of the Headers in a HttpWebResponseMessage using the ApiControlle

Time:02-01

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.

CodePudding user response:

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.

  • Related