'URL mapping with C# HttpListener

In the code below I am waiting for any call to the 8080 port.

public static void Main()
{
    HttpListener listener = new HttpListener();
    listener.Prefixes.Add("http://*:8080/");
    
    listener.Start();
    
    while(isRunning)
    {
        HttpListenerContext ctx = listener.GetContext();
        new Thread(new Worker(ctx).ProcessRequest).Start();
    }
}

Is it possible to map specific URL patterns to different behavior? I want achieve a REST-style server i.e. a call to localhost:8080/person/1 will launch getPersonHandler(int)

[Mapping("*:8080/person/$id")]
public void getPersonHandler(int id)
{
   // ...
}

The Mapping syntax is just my wishful analogy to JAX-RS libraries that I know. I would like to do the same in C# (desktop C#, not asp).



Solution 1:[1]

If you are working in .NET 4.0 or higher and looking for a pre-existing REST server solution that you can plug into (which it sounds like you are), you might want to check out Grapevine. You can get it using NuGet, and the project wiki has lots of sample code. Plus, it is open source, so if you just wanted to see how it can be accomplished, you can see all the source code there.

You can filter requests by path info (using regular expressions) and request methods (GET, POST, etc.).

I am the project author, and I had a similar need as the one you described. Using resources I found here and elsewhere, I built Grapevine so that I would have a solution in my back pocket whenever I needed it again (DRY).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1