create a http server with a custom route in csharp

To create an HTTP server with custom routing in C#, you can use the HttpListener class from the System.Net namespace. Here's an example:

main.cs
using System;
using System.Net;

class HttpServer
{
    private readonly HttpListener listener;

    public HttpServer(string prefix)
    {
        listener = new HttpListener();
        listener.Prefixes.Add(prefix);
    }

    public void Start()
    {
        listener.Start();
        Console.WriteLine($"Server started on {listener.Prefixes.First()}");

        while (true)
        {
            var context = listener.GetContext();
            HandleRequest(context);
        }
    }

    private void HandleRequest(HttpListenerContext context)
    {
        var request = context.Request;
        var response = context.Response;

        // Implement your own routing logic here
        if (request.HttpMethod == "GET" && request.Url.PathAndQuery == "/hello")
        {
            response.ContentType = "text/plain";
            response.StatusCode = 200;
            var data = System.Text.Encoding.UTF8.GetBytes("Hello, World!");
            response.OutputStream.Write(data, 0, data.Length);
        }
        else
        {
            response.ContentType = "text/plain";
            response.StatusCode = 404;
            var data = System.Text.Encoding.UTF8.GetBytes("Page not found");
            response.OutputStream.Write(data, 0, data.Length);
        }

        response.OutputStream.Close();
    }
}
1325 chars
50 lines

In the above code, we define a custom class HttpServer that takes a prefix as an argument in its constructor. The prefix is the URL that the server should listen to. The Start method starts the server and listens for incoming requests.

The HandleRequest method is responsible for handling incoming requests. It checks the HTTP method and URL of the request and returns a response accordingly.

To use this class, you can simply create an instance of HttpServer and call its Start method:

main.cs
var server = new HttpServer("http://localhost:8080/");
server.Start();
71 chars
3 lines

This will start the server and listen for incoming requests on http://localhost:8080/. When you navigate to http://localhost:8080/hello in your web browser, you should see the message "Hello, World!" returned by the server.

gistlibby LogSnag