Question

I would like to have nancy rule that matches/captures all url segments after the initial match.

For example I would like to do this:

have a url like: /views/viewname/pageid/visitid/someother

and a rule like this:

Get["/views/{view}/{all other values}"] = parameters =>
 {
    string view = parameters.view;

    List<string> listOfOtherValues = all other parameters..

    return ...
 };

listOfOtherValues would end up being:

  • pageid
  • visitid
  • someother

I would also like to do this for querystring parameters.

given the a url like: /views/viewname?pageid=1&visitid=34&someother=hello

then listOfOtherValues would end up being:

  • 1
  • 34
  • hello

Is this even possible with Nancy?

Was it helpful?

Solution

For your first problem you can use regular expression as well as simple names to define your capture groups. So you just define a catch all RegEx.
For your second, you just need to enumerate through the Request.Query dictionary.

Here is some code that demonstrates both in a single route.

public class CustomModule : NancyModule
{
    public CustomModule() {
        Get["/views/{view}/(?<all>.*)"] = Render;
    }

    private Response Render(dynamic parameters) {
        String result = "View: " + parameters.view + "<br/>";
        foreach (var other in ((string)parameters.all).Split('/'))
            result += other + "<br/>";

        foreach (var name in Request.Query)
            result += name + ": " + Request.Query[name] + "<br/>";

        return result;
    }
}

With this in place you can call a URL such as /views/home/abc/def/ghi/?x=1&y=2 and get the output View: home
abc
def
ghi
x: 1
y: 2

Note: The foreach over Request.Query is support in v0.9+

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top