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.

commit 93b7ace · authored · amended · 1 min read

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

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);
}

local graph · open full graph

"ASP.NET Core - Handling Custom Header on Request/Response" is connected to the topics ASP.NET Core and related to 6 other entries. ASP.NET Core - OAuth 2.0 Client Access Token Management ASP.NET Core - OAuth 2.0 Cl… ASP.NET Core - Using Mutliple Authentication Schemes ASP.NET Core - Using Mutlip… Serilog - Console Sink Themes Serilog - Console Sink Them… Azure DevOps Build - Could not locate the assembly Azure DevOps Build - Could … .NET Core API Gateway Ocelot - Logging HTTP Requests & Response Including Headers & Body .NET Core API Gateway Ocelo… ASP.NET Core - Return 500 (Internal Server Error) or any other Status Code from API ASP.NET Core - Return 500 (… ASP.NET Core #aspnet-core ASP.NET Core - Handling Custom He…

comments

loading discussion…