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);
}
});
});
}