Thursday, June 1, 2023

Create an HTTPS Server With HTTP listener in C#.NET, VB.NET

Using the HTTPSLISTENER we can monitor all the HTTP comunications happenining through the system. You can make self hosted application with HTTPListener easily. The sample code to setup a self-hosted API application server is below.

var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:1234/");
listener.Start();
Console.WriteLine("Listening on port 1234...");

while (true)
{
HttpListenerContext context = listener.GetContext();
HttpListenerRequest req = context.Request;
HttpListenerResponse resp = context.Response;
resp.Headers.Set("Content-Type", "application/json");
string data = "Hello WORLD";
byte[] buffer = Encoding.UTF8.GetBytes(data);
resp.ContentLength64 = buffer.Length;
System.IO.Stream ros = resp.OutputStream;
ros.Write(buffer, 0, buffer.Length);
}



Using the above sample code you can accept the HTTPSRequests and reply to the requests. The main drawback for the above code is it is not safe. To make it safe communication you have to use HTTPS protocol. To work with HTTPS protocol you have to create SSL certificate and install it on a port be following the steps below.

Step 1 : Create an SSL certificate in your PC
---------------------------------------------------------


To do this open windows powershell in administrator previleges and type below and hit enter

New-SelfSignedCertificate -CertStoreLocation Cert:\LocalMachine\My -DnsName "mylocalsite.local" -FriendlyName "MyLocalSiteCert" -NotAfter (Get-Date).AddYears(10)

Now you created a SSL certificate with "mylocalsite.local" and you can get the Thumbprint. Copy the thumpprint and run the netsh command as below.

netsh http add sslcert ipport=0.0.0.0:(Port Number eg:6000) certhash=(Thumbprint) appid='{00112233-4455-6677-8899-AABBCCDDEEFF}'

Now you can open the port in your browser like https://localhost:8000/

Step2 : Now try the below code

var listener = new HttpListener();
listener.Prefixes.Add("https://localhost:8000/");
listener.Start();

while (true)

{ HttpListenerContext context = listener.GetContext();

HttpListenerRequest req = context.Request;

HttpListenerResponse resp = context.Response;
resp.Headers.Set("Content-Type", "application/json");
string data = "Hello WORLD";
byte[] buffer = Encoding.UTF8.GetBytes(data);
resp.ContentLength64 = buffer.Length;
System.IO.Stream ros = resp.OutputStream;
ros.Write(buffer, 0, buffer.Length);
}

Visit my sites : Lanyards In UAE Badge Printer Dubai