Skip to content

Instantly share code, notes, and snippets.

@thecodejunkie
Created January 17, 2017 12:45
Show Gist options
  • Save thecodejunkie/f0551b90084eee3e4e1caecb07f79eed to your computer and use it in GitHub Desktop.
Save thecodejunkie/f0551b90084eee3e4e1caecb07f79eed to your computer and use it in GitHub Desktop.
Sample of a custom IRouteResolver
public class MyRouteModule : NancyModule
{
public MyRouteModule()
{
Get("/", _ =>
{
return "Hi";
});
Post("/", _ =>
{
return "Hi from a post route";
});
Delete("/foo", _ =>
{
return "Hi from a delete";
});
}
}
public class MyRouteResolver : IRouteResolver
{
private readonly IRouteCache routeCache;
private readonly INancyModuleCatalog catalog;
private readonly INancyModuleBuilder moduleBuilder;
public MyRouteResolver(IRouteCache routeCache, INancyModuleCatalog catalog, INancyModuleBuilder moduleBuilder)
{
this.routeCache = routeCache;
this.catalog = catalog;
this.moduleBuilder = moduleBuilder;
}
public ResolveResult Resolve(NancyContext context)
{
var parts =
context.Request.Path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var method = parts[0];
var path =
string.Join("/", parts.Skip(1).ToArray());
if (!path.StartsWith("/"))
{
path = "/" + path;
}
foreach (var entry in this.routeCache)
{
// Get the RouteDescription entires
foreach (var tuple in entry.Value)
{
var routeIndex = tuple.Item1;
var routeDescription = tuple.Item2;
// If the method declared route does not match the requested method, skip it
if (!routeDescription.Method.Equals(method, StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (routeDescription.Path.Equals(path))
{
return this.GetMatchingRoute(context, entry, routeIndex);
}
}
}
return GetNotFoundResult(context);
}
private ResolveResult GetMatchingRoute(NancyContext context, KeyValuePair<Type, List<Tuple<int, RouteDescription>>> entry, int routeIndex)
{
var module = this.moduleBuilder.BuildModule(
this.catalog.GetModule(entry.Key, context), // entry.Key contains a Type of the NancyModule that the matched route belongs to
context);
return new ResolveResult
{
Route = module.Routes.ElementAt(routeIndex),
Parameters = DynamicDictionary.Empty, // We are not capturing any parameters
Before = module.Before,
After = module.After,
OnError = module.OnError
};
}
private static ResolveResult GetNotFoundResult(NancyContext context)
{
return new ResolveResult
{
Route = new NotFoundRoute(context.Request.Method, context.Request.Path),
Parameters = DynamicDictionary.Empty,
Before = null,
After = null,
OnError = null
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment