DEV Community

moniisek
moniisek

Posted on • Edited on

Azure functions isolated worker HTTP trigger: custom header disappears from response.

So I had a simple Azure function like this:

public async Task<HttpResponseData> GetCountries(
    [HttpTrigger(AuthorizationLevel.Function, "get", Route = "countries")] HttpRequestData req, FunctionContext ctx)
{
    var result = await _countriesService.GetCountries();            
    var response = req.CreateResponse(HttpStatusCode.OK);    
    await response.WriteAsJsonAsync(result);   
// ctx.GetCorrelationId() is an extension method on the FunctionContext 
    response.Headers.Add("x-correlationId", ctx.GetCorrelationId());        
    return response;
}
Enter fullscreen mode Exit fullscreen mode

When I stopped on the line return response with debugger, I saw that the response did indeed contain the custom header 'x-correlationId'. However, the client (I tried Postman and browser) did not receive this header.

The solution was to first insert the custom header, and then write the body into it. So the sequence is:

response.Headers.Add("x-correlationId", ctx.GetCorrelationId());
await response.WriteAsJsonAsync(result);    
Enter fullscreen mode Exit fullscreen mode

Unfortunately, I don't know what was really happening here. Why the debugger showed me that the header was there even though the response was somehow modified by the WriteAsJsonAsync method.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay