Skip to content

Instantly share code, notes, and snippets.

@justinyoo
Created November 24, 2016 01:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinyoo/8080c2beb670ff090771d5bf29f6f626 to your computer and use it in GitHub Desktop.
Save justinyoo/8080c2beb670ff090771d5bf29f6f626 to your computer and use it in GitHub Desktop.
Implementing HTTP Request Handler on ASP.NET Core Applications
public class HttpRequestHeaderHandlerMiddleware
{
private readonly RequestDelegate _next;
...
public HttpRequestHeaderHandlerMiddleware(RequestDelegate next, ...)
{
this._next = next;
...
}
public async Task Invoke(HttpContext context)
{
...
await this.ProcessRequestAsync(..., context).ConfigureAwait(false);
}
private async Task ProcessRequestAsync(..., HttpContext context)
{
var uri = BuildUri(url, context);
using (var client = new HttpClient())
{
...
// Add custom headers.
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
var result = await client.GetAsync(uri).ConfigureAwait(false);
context.Response.StatusCode = (int)result.StatusCode;
if (result.Content.Headers.ContentType != null)
{
context.Response.ContentType = result.Content.Headers.ContentType.MediaType;
}
var response = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
await context.Response.WriteAsync(response, Encoding.UTF8).ConfigureAwait(false);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment