Reputation: 1973
I'm implementing an API via a web service, using Nancy.
I'd like to have a /help or /docs page that programmatically lists all of the available routes, so that I can provide API users with automatically generated/updated documentation.
Any ideas on how to accomplish this? (Inside a route handler, "this.routes" gives access to a collection of defined routes - but only on the current NancyModule. I'd need a programmatic way to list all registered routes, not just ones in the current module)
Upvotes: 7
Views: 3418
Reputation: 24450
Example of how to use IRouteCacheProvider
like @grumpydev mentioned in this answer:
// 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; }
}
You can get the routing information like Path
and Method
from the list of Nancy.Routing.RouteDescription
. For example with this view:
<!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>
Upvotes: 0
Reputation: 1159
Not exactly what you need, but there is also a built in dashboard panel in Nancy. To enable it do:
public class CustomBootstrapper : DefaultNancyBootstrapper
{
protected override DiagnosticsConfiguration DiagnosticsConfiguration
{
get { return new DiagnosticsConfiguration { Password = @"secret"}; }
}
}
And then you can access it on {yournancyapp}/_nancy
https://github.com/NancyFx/Nancy/wiki/Diagnostics
Upvotes: 10
Reputation: 26599
You can do it by taking a dependency on the IRouteCacheProvider and calling GetCache - we actually do this in one of our demos in the main repo:
https://github.com/NancyFx/Nancy/blob/master/src/Nancy.Demo.Hosting.Aspnet/MainModule.cs#L13
Upvotes: 8