Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom header to ASP.NET Core Web API response

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?

like image 294
JDawg Avatar asked Sep 12 '17 18:09

JDawg


People also ask

How do I set up response headers?

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.

How do I get custom header values in net core API?

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.

Can I add custom header to HTTP request?

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.


3 Answers

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();
}    
like image 61
Timothy Macharia Avatar answered Oct 12 '22 19:10

Timothy Macharia


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"]
like image 32
Dmitry Pavlov Avatar answered Oct 12 '22 17:10

Dmitry Pavlov


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.

like image 40
HO3EiN Avatar answered Oct 12 '22 19:10

HO3EiN