using Microsoft.AspNetCore.Mvc; namespace GitRepoViewer.CorsProxy.Controllers; [ApiController] // [Route("[controller]")] [Route("/")] public class SimpleProxyController : ControllerBase { private readonly ILogger _logger; public SimpleProxyController(ILogger logger) { _logger = logger; } [HttpGet("get/{*url}")] public async Task Get(string url) { _logger.LogInformation("Proxying url: " + url); var request = new HttpRequestMessage(HttpMethod.Get, url); var client = new HttpClient(); var response = await client.SendAsync(request); if(!response.IsSuccessStatusCode) _logger.LogWarning("Got status code: " + response.StatusCode + " for url: " + url); //throw new Exception("Failed to fetch file: " + url); Response.StatusCode = (int) response.StatusCode; Response.ContentType = response.Content.Headers.ContentType?.MediaType ?? "application/octet-stream"; //copy headers foreach (var (key, value) in response.Headers) { Response.Headers.Add(key, value.ToArray()); } //override cors Response.Headers.Add("Access-Control-Allow-Origin", "*"); Response.Headers.Add("Access-Control-Allow-Headers", "*"); Response.Headers.Add("Access-Control-Allow-Methods", "*"); Response.Headers.Add("Access-Control-Allow-Credentials", "true"); Response.Headers.Add("Access-Control-Max-Age", "86400"); await response.Content.CopyToAsync(Response.Body); //return new FileStreamResult(await response.Content.ReadAsStreamAsync(), response.Content.Headers.ContentType?.MediaType ?? "application/octet-stream"); } }