How to add custom header to ASP.NET Core Web API response
You can just hi-jack the HttpContext
from the incoming Http Request
and add your own custom headers to the Response
object before calling return.
If you want your custom header to persist and be added in all API requests across multiple controllers, you should then consider making a Middleware
component that does this for you and then add it in the Http Request Pipeline in Startup.cs
public IActionResult SendResponse()
{
Response.Headers.Add("X-Total-Count", "20");
return Ok();
}
There is an example for simple GET
action which returns top X
records from some list as well as the count
in the response header X-Total-Count
:
using System;
using System.Linq;
using System.Net;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication.Controllers
{
[Route("api")]
public class ValuesController : Controller
{
[HttpGet]
[Route("values/{top}")]
public IActionResult Get(int top)
{
// Generate dummy values
var list = Enumerable.Range(0, DateTime.Now.Second)
.Select(i => $"Value {i}")
.ToList();
list.Reverse();
var result = new ObjectResult(list.Take(top))
{
StatusCode = (int)HttpStatusCode.OK
};
Response.Headers.Add("X-Total-Count", list.Count.ToString());
return result;
}
}
}
URL looks like http://localhost:3377/api/values/5
and results (for 19 dummy records generated, so X-Total-Count
value will be 19) are like:
["Value 18","Value 17","Value 16","Value 15","Value 14"]