So when you are writing your own Router you implement from the IRouter
interface. Which forces you to implement the following two methods.
VirtualPathData GetVirtualPath(VirtualPathContext context)
Task RouteAsync(RouteContext routeContext)
I understood that the RouteAsync
method will get called upon every request and should handle the routing itself. So what about the GetVirtualPath
method. For now I use it something along these lines:
public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
return null;
}
Which works perfectly fine for now. Now the actual question
The first method, GetVirtualPath, is used internally by the framework to generate urls based on this route in methods like the HTML.ActionLink one, the second method, RouteAsync, is where our logic will really reside.
Our class should start with something like this:
public class MyRouter : IRouter
{
private readonly IRouter _defaultRouter;
public MyRouter (IRouter defaultRouter)
{
_defaultRouter = defaultRouter;
}
public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
return _defaultRouter.GetVirtualPath(context);
}
public async Task RouteAsync(RouteContext context)
{
}
}
From the URL generation with LinkGenerator
URL generation is the process by which routing can create a URL path based on a set of route values. This allows for a logical separation between route handlers and the URLs that access them.
URL generation follows a similar iterative process, but it starts with user or framework code calling into the GetVirtualPath method of the route collection. Each route has its GetVirtualPath method called in sequence until a non-null VirtualPathData is returned.
Besides,asp.net core has Route class to implement of IRouter
Routing provides the Route class as the standard implementation of IRouter. Route uses the route template syntax to define patterns to match against the URL path when RouteAsync is called. Route uses the same route template to generate a URL when GetVirtualPath is called.