Home » C# » Expose a custom header for pagination in a Net Core API

Expose a custom header for pagination in a Net Core API

By Emily

During a recent project building a .Net Core 6 API, I was developing an endpoint that would return a list of products. As that list could potentially be very long I need to paginate the data.

In order for the response body to be in the same format as the other endpoints, I needed to return the pagination data in a custom HTTP response header rather than in the JSON response itself.

Although I could see the custom header in Postman, I couldn’t access it from the React front end code. That’s because a custom header needs to be specifically exposed in a .Net Core API as well as added to the HTTP response. This post explains how to expose and set the custom response header.

Expose a custom HTTP response header in C#

Within the same block of code that you set up your allowed origins in your Cors policy in program.cs, use the withExposedHeaders method.

builder.Services.AddCors(corsOptions =>
{
    //set up a Cors policy
    corsOptions.AddPolicy("corspolicy", builder =>
        {
            builder.WithOrigins(apiSettings.AllowedOrigins)
                .AllowAnyHeader()
                //specify any custom headers to be exposed
                .WithExposedHeaders("X-Pagination")
                .AllowAnyMethod()
                .AllowCredentials();            
        });
});

If you’re not sure what apiSettings.AllowedOrigins is and where it comes from, please read how to get values from appsettings file.


Set the value of the custom response header

Now that you’ve exposed the custom header, you need to set the value of it in the Controller using Response.Headers.Add(name,value) :

[HttpGet("list")]
public async Task<IActionResult> GetProducts()
{  	
    //get the data
    List<Product> data = await GetList();

    //build the object that we are going to return in the header
    PaginationDto paginationDto = new PaginationDto()
    {
      TotalCount = data.TotalCount,
      PageSize = data.PageSize,
      CurrentPage = data.CurrentPage,
      TotalPages = data.TotalPages,
      HasNext = data.HasNext,
      HasPrevious = data.HasPrevious
    };
	
  	//set the value of the custom header
    Response.Headers.Add(
      "X-Pagination",
      JsonConvert.SerializeObject(paginationDto));
	
    //return the data
    return Ok(products);
 } 

Check custom response header in Postman

Using Postman to request the data from the endpoint we get a successful response body of data back. Select headers from the response dropdown and you can see the custom header:

Set the custom http response header in Net Core API

It’s important to be aware of the fact that even if you haven’t exposed the header correctly in your C# code you will still be able to see the header in Postman but you won’t be able to access it from your front end code.

As long as you’ve followed the steps in this post, you will now be able to get the value from the custom header in your front end code.

You may be interested in: