http listener with https support coded in c#

2019-03-04 17:47发布

I found a lot of answers how to set httplistener up to use HTTPS, but each one solution requires the use of command line. I guess that is the fastest way to do it but I would like to write C# class to handle this.

In old solution I used webserver class (found somewhere on Internet, I don't remember exact name) which allowed to add certificate in that way:

webserver.Certificate = new X509Certificate2("MyCert.pfx", "MyPassword");

Is there way to achieve this with httplistener? From code obviously.

Regards.

1条回答
贪生不怕死
2楼-- · 2019-03-04 18:33

You can load a certificate with:

X509Certificate cert = new X509Certificate2("MyCert.pfx");

And then install it:

X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
if (!store.Certificates.Contains(cert))
{
    store.Add(cert);
}
store.Close();

Of course you might have to change the store name or location for your particular app.

For running the netsh command, you could look into creating and running a process (i.e. Process.Start) and run netsh.exe. Otherwise you have to mess with the Win32 HttpSetServiceConfiguration function, or the .NET equivalent if there is one.

You might find this codebox article useful: http://dotnetcodebox.blogspot.com/2012/01/how-to-work-with-ssl-certificate.html

查看更多
登录 后发表回答