【问题标题】:Capture all url segments after the initial match with Nancy在与 Nancy 初始匹配后捕获所有 url 段
【发布时间】:2011-11-03 06:49:06
【问题描述】:

我想要在初始匹配后匹配/捕获所有 url 段的 nancy 规则。

例如我想这样做:

有一个类似的网址:/views/viewname/pageid/visitid/someother

还有这样的规则:

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

    List<string> listOfOtherValues = all other parameters..

    return ...
 };

listOfOtherValues 最终会是:

  • 页面标识
  • 访问
  • 另一个

我也想对查询字符串参数执行此操作。

给定一个网址,例如:/views/viewname?pageid=1&visitid=34&someother=hello

那么 listOfOtherValues 最终会是:

  • 1
  • 34
  • 你好

南希也能做到这一点吗?

【问题讨论】:

    标签: nancy


    【解决方案1】:

    对于您的第一个问题,您可以使用正则表达式以及简单的名称来定义您的捕获组。因此,您只需定义一个包罗万象的 RegEx。
    对于第二个,您只需要枚举 Request.Query 字典。

    这里有一些代码在一条路线中演示了这两种方法。

    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;
        }
    }
    

    有了这个,你可以调用一个 URL,比如/views/home/abc/def/ghi/?x=1&amp;y=2 并得到输出 View: home
    abc
    def
    ghi
    x: 1
    y: 2

    注意: foreach over Request.Query 在 v0.9+ 中得到支持

    【讨论】:

    • 在你的第一个例子中,为什么我不能匹配 /views/home/1.2 之类的东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 2015-08-03
    • 1970-01-01
    • 2014-08-07
    相关资源
    最近更新 更多