Last active
March 17, 2020 15:50
-
-
Save bjornharrtell/b1a56803ab7fc473afaf92f8b4cc0219 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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