When we create a module inside a NancyFX app, we do routing this way:
public class HappyModule : Nancy.NancyModule
{
public HappyModule() : base("/Happy")
{
Get["/"] = _ => "Received GET request";
}
}
So, when we hit http://<host>:<port>/Happy/
, we get the expected response. However, I think that hard-coding routes is not a "very-maintainable" thing to do (specially on large systems), so the question is: Is there a way to set a convention or something that make routes being named by its respective module name, so this way I must not always need to extend/hard-code route the base NancyModule
constructor?
What I really want to know is: Is there a routing mechanism similar to that one we have in ASP.NET WebApi (code below)?
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
The short answer to your question it nope. We don't support route conventions in Nancy.
In my personal experience, every project I've worked on I've swayed away from the conventions in MVC and ended up using Attribute Routing. The conventions only get you so far before you're like "wait, how do I get to this route again?"
Then you end up sifting through files trying to figure out where the route is registered.
APIs should be defined once and rarely ever need to change, if ever. Defining the route close to the implementation ensures that you can easily find things.
The base path allows you to define area's of a site though. For example rather than writing /admin
everywhere, you could define an abstract module for the admin area.
public abstract class AdminModule : NancyModule
{
public AdminModule() : base("/admin"){}
public AdminModule(string path) : base("/admin/" + path.TrimStart('/')){}
}
Something like this, where all admin modules inherit from this to ensure all paths are prefixed with /admin