Skip to content

Instantly share code, notes, and snippets.

@ArtemAvramenko
Created August 2, 2021 10:54
Show Gist options
  • Save ArtemAvramenko/482a402a1183a646511219f8cee75fad to your computer and use it in GitHub Desktop.
Save ArtemAvramenko/482a402a1183a646511219f8cee75fad to your computer and use it in GitHub Desktop.
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
namespace Microsoft.Extensions.Hosting
{
public static class KestrelServerOptionsExtensions
{
public static void ConfigureEndpoints(this KestrelServerOptions options)
{
var urls = Environment
.GetEnvironmentVariable("ASPNETCORE_URLS")
.Split(";")
.Select(_ => new Uri(_));
var inDocker = Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") == "true";
var url = urls.FirstOrDefault(_ => _.Scheme == (inDocker ? "http" : "https")) ?? urls.First();
options.Listen(IPAddress.Any, url.Port, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
if (!inDocker)
{
listenOptions.UseHttps(GetDebugCertificate());
}
});
}
private static X509Certificate2 GetDebugCertificate()
{
var request = (FtpWebRequest)WebRequest.Create("ftp://server.local/certificates/mycert.pfx");
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential("user", "password");
using var response = (FtpWebResponse)request.GetResponse();
using var responseStream = response.GetResponseStream();
using var memoryStream = new MemoryStream();
responseStream.CopyTo(memoryStream);
var certData = memoryStream.ToArray();
return new X509Certificate2(certData, "pfx_password");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment