I am porting my API from Web API 2 to ASP.NET Core Web API. I used to be able to add a custom header in the following manner:
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add("X-Total-Count", count.ToString());
return ResponseMessage(response);
How does one add a custom header in ASP.NET Core Web API?
Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.
Using IHTTPContextAccessor to extract custom header The above–discussed HttpContext or Request class gives us access to metadata including headers of given HttpContext within Controller. However, if you need to access headers or any HttpContext metadata in other services or modules then please use IHTTPContextAccessor.
In the Home pane, double-click HTTP Response Headers. In the HTTP Response Headers pane, click Add... in the Actions pane. In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.
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"]
For anyone who want to add custom header to all requests, middleware is the best way. make some change in startup.cs like this:
app.Use(async (context, next) =>
{
context.Response.Headers.Add("X-Developed-By", "Your Name");
await next.Invoke();
});
Good luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With