How to add custom header in Asp.net Core Web API Response [3 Ways for security]

/ / 0 Comments

Asp.net Core add custom header response:  Here in this article will see how to add custom header response in Asp.net Core Web API. Now the question why do I add a custom header to the Asp.net Core application. The simple answer is, I have a requirement where on GET request I have to return the server's last syncing date in the response header.

Another example is in one endpoint I have returned a list of data, and its counts are set in the custom header response. 

Another best usage is to modify the response header in Asp.net Core for adding security headers.

Security headers are a fundamental part of website security. These headers protect the website against XXX, code injection, and clickjacking.

Some examples of security headers are by setting response header for X-Content-Type-Options as nosniff, X-Frame-Options as  DENY, and X-XSS-Protection as 1; mode=block.

Here we learn 3 different ways to add or modify the response header in the Asp.net Core application. 

Below 3 approaches to add custom header in Asp.net core

  1. Globally add custom header to all the responses using middleware at startup.cs.
  2. Add custom header at IAction method using  HttpContext.
  3. Add Custom header to Controller / Action method level using Filters.

#1 Globally Add Custom Header to all the responses in Asp.net Core

Here we see how to add custom header globally in our whole Asp.net Core application response. Here we use in-line middleware in our Startup.cs file under Configure method to add custom headers.

Common usage of this approach is when we want to add a common header for all the responses.

Like company branding by mentioning developed by company name or like adding security headers on the overall application response.

Code to append custom response header globally is as written below:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    
	app.Use(async (context, next) =>
	{
		context.Response.Headers.Add("X-Codepedia-Custom-Header-Response", "Satinder singh");    
		context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
		context.Response.Headers.Add("X-Frame-Options", "DENY");
		context.Response.Headers.Add("X-XSS-Protection", "1; mode=block");                
		await next();
	});
	
	// your other code
}


Here is the output, which displays the security header and our custom header in the response.




#2 Add Custom header at IAction method in Asp.net Core

Here we add a custom header at the IAction method level. If we want to add the custom header for a specific action method, then we use this approach.

Here we use HttpContext class and using Response.Headers.Add() method we able to add custom header in the IAction method response.

Code as written below:

[HttpGet]
[Route("GetEmployee")]
public IActionResult GetAllEmployee()
{
	var obj = new Employee
	{
		Name = "Satinder singh",
		Location = "Mumbai",
		Job = "Full-Stack Developer"
	};

	HttpContext.Response.Headers.Add("x-custom-header-from-action 1", "my custom value 1");
	
	//HttpContext.Response.Headers.Add("x-total-count", "MyCountValue");

	// Or we can also use httpContextAccessor as written below
	// httpContextAccessor.HttpContext.Response.Headers.Add("x-set-custom-header", "custom value"); 

	return Ok(obj);
}


Here is the output of our Web API response, wherein response header we got our custom header.

add custom header response using httpcontext in Aspnet Core

#4 Add Custom header to Controller / Action method level using Filters in Asp.net Core

Here in the 3rd approach, to add a custom header we use filters. First, we create a new Asp.net core project. Now under our project, we create a new folder as "Attribute".

Under the attribute folder, we add a new class file named as AllowCrossSiteAttribute.cs. 

In our class will inherit ResultFilterAttribute and override the method OnResultExecuting. Note we need to add Microsoft.AspNetCore.Mvc.Filters namespace in our controller.

Our final code looks like as written below:

  public class AllowCrossSiteAttribute : ResultFilterAttribute
  {
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            context.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            base.OnResultExecuting(context);
        }
  }

Now we add this attribute to our controller action method:

[HttpGet]  
[AllowCrossSite]
public IActionResult GetEmployeData()
{
 // .. your logic code
}

That's it now in our response will get the header as "Access-Control-Allow-Origin" as "*".

Additionally, we can add this attribute at our controller level, code as written below:

[Route("api/[controller]")]
[ApiController]
[AllowCrossSite]
public class EmployeeController : ControllerBase
{
  //...
  // other code logic
}     

Here is our output of adding custom header response using filters in Asp.net Core.


Conclusion: Here we learn how using any of these 3 ways we can add custom response header in Asp.net Core. Also, we can modify response headers globally using inline-middleware at startup.cs.

Other References:

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

0 Comments