Alter response header in Web API to return machine name

Full source code available here.

I recently hit a problem where I was getting incorrect responses from a server behind a load balancer. Looking at the logs didn’t help because there was no error.

It was likely due to a misconfigured environmental variable but I couldn’t even identify which server was having the problem because of the load balancer.

Luckily the application was a .NET Core Web Api and I could use a little bit of middleware to add the server name to the response header.

It’s a trivial change in the Configure(..) method of Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Use((context, next) =>
    {
        context.Response.Headers.Add("MachineName", $"{Environment.MachineName}");
        return next();
    });
    app.UseMvc();
}

That’s all I had to do.

Here’s how the response looks now.

.

Full source code available here.