Wednesday, May 20, 2020

Step by step how to add custom headers using Asp.Net Core 3.0

In this tutorial we'll learn   how to add custom headers using Asp.Net Core 3.0 
We'll use Postman for testing purposes of a RESTful WEBAPI Core application, sending  HTTP POST requests. We'll start with a WebApi Core 3.0 application,  and we'll add an Extension Method to the Response class in order to append our headers.
See the code here:
https://github.com/CarmelSchvartzman/DOTNET/blob/master/HEADERS/ADD_HEADERS_EXTENSIONMETHOD





Step by step how to add custom headers using Asp.Net Core 3.0



First, we create a new Extension Method to the Response class in order to append our headers., in Visual Studio, as follows:





  public static class Extensions
    {
        public static void AddApplicationError(this HttpResponse response, string msg)
        {
            response.Headers.Add("Carmel-Error", msg);
            response.Headers.Add("Access-Control-Expose-Headers", "Carmel-Error");
            response.Headers.Add("Access-Control-Allow-Origin", "*");
        }

    }

On the startup.cs file , we add to  the Configure method , the following code:

  if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(b => {
                    b.Run(async ctx => {
                        ctx.Response.StatusCode = (int) 
HttpStatusCode.InternalServerError;
                        var err = ctx.Features.Get<IExceptionHandlerFeature>();
                        if (err != null)
                        {
                            ctx.Response.AddApplicationError(err.Error.Message);
                            await  ctx.Response.WriteAsync(err.Error.Message);
                        }
                         
                    });
                });
            }

This code catchs all exceptions globally, and also adds our headers to the response.
Send a request using Postman, and open the "headers" window to see them:












That's all.... 
In this tutorial we've seen  how to add custom headers using Asp.Net Core 3.0  
Happy programming.....
      By Carmel Shvartzman
כתב: כרמל שוורצמן