Built in HTTP header properties

ASP.NET Core has built-in properties for commonly used HTTP headers

Home DailyDrop

Daily Knowledge Drop

ASP.NET Core has built in properties for common HTTP headers, which are faster and better than using an indexer manually.


Manual indexers

In this example, the ContextType, Date and Link headers are manually set using indexers on the endpoint response:

app.MapGet("/getheadersmanual", async context =>
{
    context.Response.Headers.ContentType = MediaTypeNames.Application.Json;
    context.Response.Headers.Date = DateTime.UtcNow.ToString();
    context.Response.Headers.Link = "/getheadersmanual";

    await context.Response.WriteAsync(@"{""Message"" : ""Look at the headers""}");
});

This works without issue, and calling the endpoint will result in the following response and headers:

{"Message" : "Look at the headers"}

Response Headers


Built-in properties

The other option is to use the built-in header properties:

app.MapGet("/getheaders", async context =>
{
    context.Response.Headers.ContentType = MediaTypeNames.Application.Json;
    context.Response.Headers.Date = DateTime.UtcNow.ToString();
    context.Response.Headers.Link = "/getheaders";

    await context.Response.WriteAsync(@"{""Message"" : ""Look at the headers""}");
});

This version will same response and headers as the above technique:

{"Message" : "Look at the headers"}

Response Headers


Notes

While the output from both techniques are effectively the same - in addition to the property method being faster than using indexers (although probably not effectively noticeable), using the property method will results in less errors and safer code, as the HTTP header name cannot be misspelt.


References

James Newton-King Tweet

Daily Drop 186: 20-10-2022

At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.

The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.
c# .net http headers