Search code examples
asp.net-coreasp.net-core-routingasp.net-core-2.2

How to dynamically resolve controller with endpoint routing?


Upgrading to asp.net core 2.2 in my hobby project there is a new routing system I want to migrate to. Previously I implemented a custom IRouter to be able to set the controller for the request dynamically. The incoming request path can be anything. I match the request against a database table containing slugs and it looks up the a matching data container class type for the resolved slug. After that I resolve a controller type that can handle the request and set the RouteData values to the current HttpContext and passing it along to the default implementation for IRouter and everything works ok.

Custom implementaion of IRouter:

public async Task RouteAsync(RouteContext context)
    {
        var requestPath = context.HttpContext.Request.Path.Value;
        var page = _pIndex.GetPage(requestPath);

        if (page != null)
        {
            var controllerType = _controllerResolver.GetController(page.PageType);
            if (controllerType != null)
            {
                var oldRouteData = context.RouteData;
                var newRouteData = new RouteData(oldRouteData);

                newRouteData.Values["pageType"] = page.PageType;
                newRouteData.Values["controller"] = controllerType.Name.Replace("Controller", "");
                newRouteData.Values["action"] = "Index";

                context.RouteData = newRouteData;

                await _defaultRouter.RouteAsync(context);
            }
        }
    }

A controller to handle a specific page type.

public class SomePageController : PageController<PageData>
{
    public ActionResult Index(PageData currentPage)
    {
        return View("Index", currentPage);
    }
}

However I got stuck when I'm trying to figure out how I can solve it using the new system. I'm not sure where I'm suppose to extend it for this behavior. I don't want to turn off the endpoint routing feature because I see an opportunity to learn something. I would aso appreciate a code sample if possible.


Solution

  • In ASP.NET 3.0 there is an new dynamic controller routing system. You can implement DynamicRouteValueTransformer.

    Documentation is on the way, look at the github issue