Skip to content

Instantly share code, notes, and snippets.

@bjornharrtell
Last active March 17, 2020 15:50
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 bjornharrtell/b1a56803ab7fc473afaf92f8b4cc0219 to your computer and use it in GitHub Desktop.
Save bjornharrtell/b1a56803ab7fc473afaf92f8b4cc0219 to your computer and use it in GitHub Desktop.
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http.Headers;
namespace DAI.Edit.Backend.WebApi.Controllers
{
[Authorize]
[Route("proxy")]
[ApiController]
public class Proxy : ControllerBase
{
public Proxy() { }
private async Task DoProxyRequest(Func<HttpClient, Task<HttpResponseMessage>> doProxyRequest)
{
using (var httpClient = new HttpClient())
{
var response = await doProxyRequest(httpClient);
Response.StatusCode = (int)response.StatusCode;
Response.ContentType = response.Content.Headers.ContentType.ToString();
Response.ContentLength = response.Content.Headers.ContentLength;
await response.Content.CopyToAsync(Response.Body, null);
await Response.CompleteAsync();
}
}
[HttpGet]
public async Task Get([FromQuery(Name = "url")] string url) =>
await DoProxyRequest(async (httpClient) =>
{
var proxyRequest = new HttpRequestMessage(HttpMethod.Get, new Uri(url));
return await httpClient.SendAsync(proxyRequest, HttpCompletionOption.ResponseHeadersRead);
});
[HttpPost]
public async Task PostStatement([FromQuery(Name = "url")] string url) =>
await DoProxyRequest(async (httpClient) =>
{
var proxyRequest = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
proxyRequest.Content = new StreamContent(Request.Body);
proxyRequest.Content.Headers.ContentType = new MediaTypeHeaderValue(Request.ContentType);
return await httpClient.SendAsync(proxyRequest, HttpCompletionOption.ResponseHeadersRead);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment