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.
- public class CustomHttpResponseMessage: HttpResponseMessage {
- public CustomHttpResponseMessage(): base() {}
- public CustomHttpResponseMessage(HttpStatusCode statusCode): base(statusCode) {
- var buildNumber = Environment.GetEnvironmentVariable("buildID");
- Headers.Add("Access-Control-Expose-Headers", "BuildNumber");
- Headers.Add("BuildNumber", buildNumber);
- }
- }
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
- {
- "extensions": {
- "http": {
- "routePrefix": "",
- "customHeaders": {
- "Access-Control-Expose-Headers": "*"
- }
- }
- },
- "version": "2.0"
- }
To receive this custom header in Angular modify the HTTP interceptor response as follows.
Import Http response,
- import {
- HttpEvent,
- HttpRequest,
- HttpResponse,
- HttpHandler,
- HttpInterceptor,
- HttpErrorResponse
- } from "@angular/common/http";
Manipulate the response of the interceptor as below.
- map((event: HttpEvent < any > ) => {
- if (event instanceof HttpResponse) {
- let builNumber = event.headers.get("BuildNumber")
- sessionStorage.setItem("BuildVersion", builNumber);
- console.log('HeaderValue', event.headers.get("BuildNumber"))
- }
- return event;
- }),
Finally, this article helps to send custom response headers and receive them on the client-side by exposing headers from Azure functions.