有没有办法列出南希应用程序中的所有可用路由?

时间:2013-03-25 20:50:14

标签: nancy

我正在使用Nancy通过Web服务实现API。

我希望有一个/ help或/ docs页面,以编程方式列出所有可用路由,以便我可以为API用户提供自动生成/更新的文档。

关于如何实现这一目标的任何想法? (在路由处理程序中,“this.routes”可以访问已定义路由的集合 - 但仅限于当前的NancyModule。我需要一种编程方式来列出所有已注册的路由,而不仅仅是当前模块中的路由)

3 个答案:

答案 0 :(得分:10)

不完全符合您的需求,但Nancy还有一个内置的仪表板面板。要启用它,请执行以下操作:

public class CustomBootstrapper : DefaultNancyBootstrapper
{
    protected override DiagnosticsConfiguration DiagnosticsConfiguration
    {
        get { return new DiagnosticsConfiguration { Password = @"secret"}; }
    }
}

然后您可以在{yournancyapp} / _ nancy

上访问它

https://github.com/NancyFx/Nancy/wiki/Diagnostics

答案 1 :(得分:8)

你可以通过依赖IRouteCacheProvider并调用GetCache来实现 - 我们实际上是在主仓库的一个演示中执行此操作:

https://github.com/NancyFx/Nancy/blob/master/src/Nancy.Demo.Hosting.Aspnet/MainModule.cs#L13

答案 2 :(得分:0)

如{@ 3}}中提到的IRouteCacheProvider如@grumpydev的示例:

// within your module
public class IndexModule : NancyModule
{
    // add dependency to IRouteCacheProvider
    public IndexModule(Nancy.Routing.IRouteCacheProvider rc)
    {
        routeCache = rc;
        Get["/"] = GetIndex;
    }

    private Nancy.Routing.IRouteCacheProvider routeCache;

    private dynamic GetIndex(dynamic arg)
    {
        var response = new IndexModel();

        // get the cached routes
        var cache = routeCache.GetCache();

        response.Routes = cache.Values.SelectMany(t => t.Select(t1 => t1.Item2));

        return response;
    }
}

public class IndexModel
{
    public IEnumerable<Nancy.Routing.RouteDescription> Routes { get; set; }
}

您可以从Path列表中获取MethodNancy.Routing.RouteDescription等路由信息。例如,使用此视图:

<!DOCTYPE html>
<html>
<body>
<p>Available routes:</p>
<table>
<thead><tr><th>URL</th><th>Method</th></tr></thead>
<tbody>
@Each.Routes
<tr><td>@Current.Path</td><td>@Current.Method</td></tr>
@EndEach
</tbody>
</table>
</body>
</html>
相关问题