Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a custom response header in ApiController

Until now, I had a GET method that looked like the following:

protected override async Task<IHttpActionResult> GetAll(QueryData query) {      // ... Some operations       //LINQ Expression based on the query parameters      Expression<Func<Entity, bool>> queryExpression = BuildQueryExpression(query);       //Begin to count all the entities in the repository      Task<int> countingEntities = repo.CountAsync(queryExpression);       //Reads an entity that will be the page start      Entity start = await repo.ReadAsync(query.Start);       //Reads all the entities starting from the start entity      IEnumerable<Entity> found = await repo.BrowseAllAsync(start, queryExpression);       //Truncates to page size      found = found.Take(query.Size);       //Number of entities returned in response      int count = found.Count();       //Number of total entities (without pagination)      int total = await countingEntities;       return Ok(new {           Total = total,           Count = count,           Last = count > 0 ? GetEntityKey(found.Last()) : default(Key),           Data = found.Select(e => IsResourceOwner(e) ? MapToOwnerDTO(e) : MapToDTO(e)).ToList()      }); } 

This worked like a charm and it was good. However, I was told recently to send the response metadata (that is, Total, Count and Last properties) as response custom headers instead of the response body.

I cannot manage to access the Response from the ApiController. I thought of a filter or attribute, but how would I get the metadata values?

I can keep all this information on the response and then have a filter that will deserialize the response before being sent to the client, and create a new one with the headers, but that seems troublesome and bad.

Is there a way to add custom headers directly from this method on an ApiController?

like image 260
Matias Cicero Avatar asked Aug 14 '15 19:08

Matias Cicero


People also ask

How do I add a response header?

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.

How do I send a custom response in Web API?

Implementing a custom response handler in Web API. Create a new Web API project in Visual Studio and save it with the name of your choice. Now, select the Web API project you have created in the Solution Explorer Window and create a Solution Folder. Create a file named CustomResponseHandler.

How do you change the header on a flask?

To set response headers in Flask and Python, we set the headers property of the response object. to call make_response to create response object that returns a string response. Finally, we return the resp object in the home route.


2 Answers

You can explicitly add custom headers in a method like so:

[HttpGet] [Route("home/students")] public HttpResponseMessage GetStudents() {        // Get students from Database         // Create the response         var response = Request.CreateResponse(HttpStatusCode.OK, students);              // Set headers for paging         response.Headers.Add("X-Students-Total-Count", students.Count());                return response; } 

For more information read this article: http://www.jerriepelser.com/blog/paging-in-aspnet-webapi-http-headers/

like image 190
Seagull Avatar answered Sep 25 '22 20:09

Seagull


I have entered comments, here is my complete answer.

You will need to create a custom filter and apply that to your controller .

public class CustomHeaderFilter : ActionFilterAttribute {     public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)     {        var count = actionExecutedContext.Request.Properties["Count"];        actionExecutedContext.Response.Content.Headers.Add("totalHeader", count);     } } 

In your Controller

  public class AddressController : ApiController         {             public async Task<Address> Get()             {                Request.Properties["Count"] = "123";             }     } 
like image 31
Yousuf Avatar answered Sep 25 '22 20:09

Yousuf