All I need to do is to modify [Connection] HTTP Header from "Keep-alive" to lowercase "keep-alive".
I wrote the class,
public class PreRequestModifications
{
private readonly RequestDelegate _next;
public PreRequestModifications(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
// Does not get called when making an HTTPWebRequest.
await _next.Invoke(context);
}
}
and registered on startup,
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware<PreRequestModifications>();
}
but the Invoke method does not get called when I execute await httpWebRequest.GetResponseAsync();
HttpWebRequest, that header is added just before sending, with no hooks you can use to alter it. You could try set.KeepAlive = false;, which should stop the header being added, then add your own header before sending, but... there is more going on behind the scenes with keep-alive connections than simply this header. It also begs the question of why the server you're calling needs it; all the HTTP specs refer to "Keep-Alive".KeepAliveis false. See the source here - line 5047. There doesn't seem much you can do about it. I'd complain to the provider of the server you're calling instead.