Home
C# Console App Web Service Absolute Basic
The Code
using System.Text;
using System.Net;
namespace Test
{
public class Program
{
public static Boolean Loop = true;
static void Main(string[] args)
{
do
{
using (HttpListener MyListen = new HttpListener())
{
MyListen.Prefixes.Add("http://localhost:8081/");
MyListen.Start();
Console.WriteLine("Listening...");
HttpListenerContext MyContext = MyListen.GetContext();
HttpListenerRequest MyRequest = MyContext.Request;
HttpListenerResponse MyResponse = MyContext.Response;
string qwe = "<html><body>";
qwe += DateTime.Now;
qwe += "</body></html>";
byte[] MyBuffer = Encoding.UTF8.GetBytes(qwe);
MyResponse.ContentLength64 = MyBuffer.Length;
Stream MyOutput = MyResponse.OutputStream;
MyOutput.Write(MyBuffer, 0, MyBuffer.Length);
}
} while (Loop == true);
}
}
}
The Explanation
No real details here because I'm only just getting to grips with this myself. This is a C# Console App that will listen for a web request and send a response. Presently the response is the current Date and Time. But I'm sure a person of your calibre would have no issue sending back whatever is required.
It strikes me as being quite a simple way of creating a self contained microservice. For example this could run on any server to which you have command line access and can start this code running. This could listen on a port, make SQL requests and return JSON or XML or HTML... or whatever the flavour of choice is.
Reader's Comments
Name
Comment
Add a RELEVANT link (not required)
Upload an image (not required)
Uploading...
Home