How To Set Custom HTTP Response Headers In C# Azure Functions And Read Them In Angular

I wrote this article as I found it difficult to send custom headers in the response of Azure functions and receive them in Angular.
 
Prepare your custom response message by manipulating HTTP response message. 
  1. public class CustomHttpResponseMessage: HttpResponseMessage {  
  2.     public CustomHttpResponseMessage(): base() {}  
  3.     public CustomHttpResponseMessage(HttpStatusCode statusCode): base(statusCode) {  
  4.         var buildNumber = Environment.GetEnvironmentVariable("buildID");  
  5.         Headers.Add("Access-Control-Expose-Headers""BuildNumber");  
  6.         Headers.Add("BuildNumber", buildNumber);  
  7.     }  
  8. }   
By default, only 6 headers are exposed which are known as CORS-safe listed response headers.
 
Below are the headers Exposed by default
 
Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma.
 
If you observe the above code, we are sending an additional header called "Access-Control-Expose-Headers"
 
This header helps to expose the required header or you can assign a "*" value to expose all headers.
 
The other way to send headers as a response in Azure functions is to modify the Host.json as follows
 
What is host.json file?
 
The host.json metadata file contains global configuration options that affect all functions for a function app 
  1. {  
  2.     "extensions": {  
  3.         "http": {  
  4.             "routePrefix""",  
  5.             "customHeaders": {  
  6.                 "Access-Control-Expose-Headers""*"  
  7.             }  
  8.         }  
  9.     },  
  10.     "version""2.0"  
  11. }  
To receive this custom header in Angular modify the HTTP interceptor response as follows.
 
Import Http response,
  1. import {  
  2.    HttpEvent,  
  3.    HttpRequest,  
  4.    HttpResponse,  
  5.    HttpHandler,  
  6.    HttpInterceptor,  
  7.    HttpErrorResponse  
  8. } from "@angular/common/http";  
Manipulate the response of the interceptor as below.
  1. map((event: HttpEvent < any > ) => {  
  2.     if (event instanceof HttpResponse) {  
  3.         let builNumber = event.headers.get("BuildNumber")  
  4.         sessionStorage.setItem("BuildVersion", builNumber);  
  5.         console.log('HeaderValue', event.headers.get("BuildNumber"))  
  6.     }  
  7.     return event;  
  8. }),  
Finally, this article helps to send custom response headers and receive them on the client-side by exposing headers from Azure functions.