create a http server with a specific route in csharp

To create an HTTP Server with a specific route in C# using .NET, you can leverage the HttpListener class.

The HttpListener class is defined within the System.Net namespace, and it provides the basic framework for implementing a simple HTTP server by allowing you to listen for incoming HTTP requests and dispatch them to your own methods.

Here’s an example of how to use HttpListener to create an HTTP Server with a specific route:

main.cs
using System;
using System.Net;

class Program {
    static void Main(string[] args) {
        string prefix = "http://localhost:8080/";
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add(prefix);
        listener.Start();
        Console.WriteLine($"Listening on {prefix}");

        while (true) {
            HttpListenerContext context = listener.GetContext();
            Console.WriteLine("Handling request...");

            if (context.Request.Url.AbsolutePath == "/specific-route") {
                HandleSpecificRoute(context);
            }

            context.Response.Close();
        }
    }

    static void HandleSpecificRoute(HttpListenerContext context) {
        // Do something with the request in this route
        context.Response.StatusCode = 200;
        context.Response.ContentType = "text/plain";
        string responseString = "Hello from the specific route!";
        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
        context.Response.ContentLength64 = buffer.Length;
        context.Response.OutputStream.Write(buffer, 0, buffer.Length);
    }
}
1137 chars
34 lines

In this example, we're setting up an HTTP listener on http://localhost:8080/ and then using an infinite while loop to listen for incoming requests. Whenever we receive a request, we check if the request URL matches a specific route (/specific-route) and, if so, we handle the request using the HandleSpecificRoute method. Finally, we close the response.

HandleSpecificRoute is an example method to handle the specific route request. You can customize this method as per your requirement.

This is a basic example to get you started with creating an HTTP Server with a specific route in C#.

gistlibby LogSnag