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.

Top comments (0)