Created
February 26, 2019 12:48
-
-
Save catlion/e6ea9727fca42041d459a94ac52b2046 to your computer and use it in GitHub Desktop.
Simple proxy service for Nuget.org
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 Microsoft.AspNetCore.Http; | |
using System; | |
using System.Linq; | |
using System.Collections.Generic; | |
using System.Net.Http; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace VTB.Portal.NugetProxy | |
{ | |
public static class Proxy | |
{ | |
const string apiUrl = "https://api.nuget.org"; | |
static HttpClientHandler handler = new HttpClientHandler | |
{ | |
PreAuthenticate = false, | |
SslProtocols = System.Security.Authentication.SslProtocols.Tls12, | |
AllowAutoRedirect = true, | |
CheckCertificateRevocationList = false, | |
ServerCertificateCustomValidationCallback = (_,x,y,z) => true, | |
MaxConnectionsPerServer = 50, | |
AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate, | |
UseCookies = true, | |
UseProxy = false | |
}; | |
static readonly HttpClient httpClient = new HttpClient(handler); | |
public static async Task Process(HttpContext ctx) | |
{ | |
var req = ctx.Request; | |
var url = apiUrl + req.Path.ToString() + req.QueryString.ToString(); | |
Console.WriteLine($"{req.Method}: {url} from {ctx.Connection.RemoteIpAddress}"); | |
using (var message = new HttpRequestMessage(new HttpMethod(req.Method), url)) | |
{ | |
if (message.Method == HttpMethod.Post || message.Method == HttpMethod.Put) | |
{ | |
message.Content = new StreamContent(req.Body); | |
} | |
foreach (var hh in req.Headers.Keys) | |
{ | |
var header = hh.ToLowerInvariant(); | |
if (header == "host" || header == "referer") | |
continue; | |
var h = req.Headers[header].ToArray(); | |
Console.WriteLine($"{header}: {h.First()}"); | |
message.Headers.TryAddWithoutValidation(header, h); | |
} | |
// send request to nuget.org | |
var resp = await httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead) | |
.ConfigureAwait(false); | |
ctx.Response.StatusCode = (int)resp.StatusCode; | |
foreach(var header in resp.Headers) | |
{ | |
ctx.Response.Headers[header.Key] = header.Value.ToArray(); | |
} | |
using (var body = await resp.Content.ReadAsStreamAsync().ConfigureAwait(false)) | |
{ | |
if (resp.StatusCode > System.Net.HttpStatusCode.Accepted) | |
{ | |
Console.WriteLine($"ERR {resp.StatusCode.ToString()}"); | |
} | |
await body.CopyToAsync(ctx.Response.Body).ConfigureAwait(false); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment