In this article, we are going to take a look at the different ways we can add Custom Headers to our ASP.NET Core Web API Responses.
Custom Headers allow us to add extra content to our HTTP requests and responses, which we can pass between the client and server. We can use custom headers for metadata, such as defining the current version of the API that is being used. We can also use them to define security policies that our applications must adhere to.
Let’s start.
VIDEO: How to Work With Custom Headers in .NET Core Application.
Adding Custom Header for Individual Response
Let’s first take a look at how to add a custom header to an individual HTTP Response.
We are going to use a basic Web API and manipulate the current HTTP Response in an API endpoint to add our custom header:
[HttpGet("individual")] public IActionResult CustomHeaderResponse() { HttpContext.Response.Headers.Add("x-my-custom-header", "individual response"); return Ok(); }
We create a very basic HTTP GET endpoint. Within this endpoint, we access the Response
object through the HttpContext
object. Then, we add a new header, with the name of x-my-custom-header
and a value of individual response
.
Testing Custom Header for Individual Response
We can test our endpoint by using Postman:
As we can see, we have a GET request to our endpoint, and in the response, we get our custom header.
This works when we only want to add a custom header to individual responses, so next, let’s take a look at some ways to add our Custom Header to multiple endpoints.
Adding Custom Header with Attributes
If we want a clean and reusable method for adding the same custom header to multiple Web API endpoints, or even at the controller level, we can define a custom attribute to achieve this.
Let’s first create a custom attribute:
public class CustomHeaderAttribute : ResultFilterAttribute { public override void OnResultExecuting(ResultExecutingContext context) { context.HttpContext.Response.Headers.Add("x-my-custom-header", "attribute response"); base.OnResultExecuting(context); } }
First of all, we create a class that inherits from the ResultFilterAttribute
abstract class, which is available in the Microsoft.AspNetCore.Mvc.Filters
namespace.
We then override the OnResultExecuting
method, which gives us access to the current HttpContext. We can use this HttpContext to add our custom header.
Finally, we call the base class OnResultExecuting
method, to ensure the response continues through the pipeline to the client.
Now that we have the attribute defined, we need to add this to a new endpoint:
[HttpGet("attribute")] [CustomHeader] public IActionResult CustomHeaderResponseFromAttribute() { return Ok(); }
This time, our endpoint is even smaller than the previous example.
We use our new CustomHeader
attribute to decorate the CustomHeaderResponseFromAttribute
action, which adds the custom header to our HTTP response. We can add this attribute to many endpoints, and also at the Controller level.
Testing Custom Header with Attributes
Again, let’s use Postman to send a GET request to our new endpoint URL of https://localhost:7026/api/custom-headers/attribute
.
We will now find our custom header, x-my-custom-header
with a value of attribute response
in the Headers section of the response, which we can apply on an endpoint or controller level.
Adding Custom Header Globally using Middleware
If we want to ensure all responses in our ASP.NET Core Web API application return a custom header, we can make use of the ASP.NET Core middleware.
We can add a custom header to the ASP.NET Core middleware in Program.cs
:
app.Use(async (context, next) => { context.Response.Headers.Add("x-my-custom-header", "middleware response"); await next(); });
Firstly, we use the IApplicationBuilder
interface and call the Use
method. We then define an anonymous async method, that takes the current HttpContext
, and the next Task to execute in the pipeline. Within this anonymous method, we add our custom header to the current response.
Finally, we need to ensure we call await next();
so that the next Task in the pipeline executes.
Testing Custom Header with Middleware
Once again, we will use Postman to send a GET request to https://localhost:7026/api/custom-headers/middleware
.
We can now find our custom header, x-my-custom-header
with a value of middleware response
in the Headers section of the response.
Enabling Custom Header with CORS Configured
What if we have an application from a different URI that uses our API?
We want to ensure the CORS policies don’t block our custom header, so let’s take a look at how to enable it.
Let’s start by enabling CORS in our Web API, in Program.cs
:
var myCorsPolicy = "MyCorsPolicy"; builder.Services.AddCors(options => { options.AddPolicy(myCorsPolicy, builder => { builder.AllowAnyOrigin() .WithExposedHeaders("x-my-custom-header"); }); }); // ... other configuration app.UseCors(myCorsPolicy);
Firstly, we define a string variable called myCorsPolicy
. Next, we call AddCors
, creating a new policy using our variable declared previously. From there we call AllowAnyOrigin
on our CorsPolicyBuilder
, which for the purposes of this demo will allow any origin to access our API. We also add WithExposedHeaders
, and here is where we add our custom header. This line is what will allow our client application to use our custom header.
Finally, we need to call UseCors
, ensuring we use the same myCorsPolicy
variable declared earlier.
Creating a Client Application to use our Custom Header
Let’s create a simple JavaScript snippet that will act as our application from a different URI, which we can run in the browser console:
fetch('https://localhost:7026/api/custom-headers/middleware') .then(response => { response.headers.forEach(function(value,name){ console.log(name + ": " + value); }); })
We can use the fetch
API to make an HTTP request to our API. Finally, with the response, we iterate over the headers and log the name and value out to the console:
The console shows us our custom header is available in the response and the JavaScript application can access it.
Conclusion
In this article, we’ve learned how to add a custom header to our ASP.NET Core Web API responses using three different techniques. We’ve also learned how to use our custom header in a client application if we have CORS enabled in our API.