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)
netsh http add sslcert ipport=0.0.0.0:(Port Number eg:6000) certhash=(Thumbprint) appid='{00112233-4455-6677-8899-AABBCCDDEEFF}'
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);
}