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.cs1325 chars50 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.cs71 chars3 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