aspnet-core

ASP.NET Core - Handling Custom Header on Request/Response

There may be situations where you want to add a custom header in your ASP.NET Core API response or you need to read a header from the request.

Abhith Rajan
Abhith RajanApril 25, 2019 · 1 min read · Last Updated:

You can access the request headers or modify the response headers easily inside the controller in your ASP.NET Core applications.

Add custom header to response

 Response.Headers.Add("your-custom-header-id", custom_header_value);

Get a request header value

 var yourHeader = Request.Headers["your-custom-header-id"].FirstOrDefault();

Get bearer token value

Another example where we get the bearer token from the Authorization header,

var authHeader = Request.Headers["Authorization"].FirstOrDefault();

if (authHeader != null && authHeader.StartsWith("Bearer", StringComparison.OrdinalIgnoreCase))
{
    var loginToken = authHeader.Replace("Bearer ", string.Empty, StringComparison.OrdinalIgnoreCase);
}

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub


Abhith Rajan

Written byAbhith Rajan
Abhith Rajan is a software engineer by day and a full-stack developer by night. He's coding for almost a decade now. He codes 🧑‍💻, write ✍️, learn 📖 and advocate 👍.
Connect

Is this page helpful?

Related ArticlesView All

Related VideosView All

Why I DON'T use MediatR in ASP.NET Core

Don't Use AutoMapper in C#! Do THIS Instead!

Exploring Source Generation for Logging

Related StoriesView All

Related Tools & ServicesView All

flurl.dev

Flurl

Flurl is a modern, fluent, asynchronous, testable, portable, buzzword-laden URL builder and HTTP client library for .NET.