skip to Main Content

How can I achieve this ‘How to create an https server’ Node.JS code in Asp.net (.Net 6)

const options = {
  key: fs.readFileSync('key.key'),
  cert: fs.readFileSync('cert.crt')
};

https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello worldn");
}).listen(8000);

I’m trying to get my domain certificate to work with my ASP.Net code but couldn’t find a solution.
Is ASP.Net even made to handle Server and Browsers communication or mainly made for APIs?

2

Answers


  1. Chosen as BEST ANSWER

    Got it by making a .pfx file (the answer) and referencing it this way: (.Net 6)

    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddControllers();
    
    //Set Certificate
    builder.Services.Configure<KestrelServerOptions>(options =>
    {
        var crt = "cert.pfx";
        var cert = new X509Certificate2(crt);
    
        options.Listen(IPAddress.Any, 80); // http
        options.Listen(IPAddress.Any, 443, listenOptions => // https
        {
            listenOptions.UseHttps(cert);
        });
    });
    
    var app = builder.Build();
    app.UseHttpsRedirection(); //MUST
    app.UseAuthorization();
    app.MapControllers();
    app.Run();
    

  2. Back when I attempted this in .NET Core 3.1 using X509Certificate2 I could not get it to work.

    What did work though was generating a .pfx certificate from the .key and .crt files in WSL (or Linux) using:

    openssl pkcs12 -export -out server.pfx -inkey server.key -in server.crt
    

    The resulting server.pfx certificate was accepted just fine by X509Certificate2.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search