summary refs log tree commit diff
path: root/GitRepoViewer.CorsProxy/Controllers/SimpleProxyController.cs
blob: 725c3751c96666c49c27d6a0a53bb0b761c18de6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using Microsoft.AspNetCore.Mvc;

namespace GitRepoViewer.CorsProxy.Controllers;

[ApiController]
// [Route("[controller]")]
[Route("/")]
public class SimpleProxyController : ControllerBase
{
    private readonly ILogger<SimpleProxyController> _logger;

    public SimpleProxyController(ILogger<SimpleProxyController> 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");
    }
}