How to achieve a dynamic controller and action method in ASP.NET MVC?

Viewed 25781

In Asp.net MVC the url structure goes like

http://example.com/{controller}/{action}/{id}

For each "controller", say http://example.com/blog, there is a BlogController.

But my {controller} portion of the url is not decided pre-hand, but it is dynamically determined at run time, how do I create a "dynamic controller" that maps anything to the same controller which then based on the value and determines what to do?

Same thing with {action}, if the {action} portion of my url is also dynamic, is there a way to program this scenario?

4 Answers

Iam working with it in .Core but i'll share it's MVC version for all, after that i will share the core version

                case OwnerType.DynamicPage:
                    var dp = mediator.Handle(new Domain.DynamicPages.DynamicPageDtoQuery { ShopId = ShopId, SeoId = seoSearchDto.Id }.AsSingle());
                    if (dp != null)
                    {
                        return GetDynamicPage(dp.Id);
                    }
                    break;

// some codes

    private ActionResult GetDynamicPage(int id)
    {
        var routeObj = new
        {
            action = "Detail",
            controller = "DynamicPage",
            id = id
        };

        var bController = DependencyResolver.Current.GetService<DynamicPageController>();
        SetControllerContext(bController, routeObj);
        return bController.Detail(id);
    }

// and

private void SetControllerContext(ControllerBase controller, object routeObj)
{
    RouteValueDictionary routeValues = new RouteValueDictionary(routeObj);

    var vpd = RouteTable.Routes["Default"].GetVirtualPath(this.ControllerContext.RequestContext, routeValues);



    RouteData routeData = new RouteData();

    foreach (KeyValuePair<string, object> kvp in routeValues)
    {
        routeData.Values.Add(kvp.Key, kvp.Value);
    }

    foreach (KeyValuePair<string, object> kvp in vpd.DataTokens)
    {
        routeData.DataTokens.Add(kvp.Key, kvp.Value);
    }


    routeData.Route = vpd.Route;
    if (routeData.RouteHandler == null)
        routeData.RouteHandler = new MvcRouteHandler();


    controller.ControllerContext = new ControllerContext(this.ControllerContext.HttpContext, routeData, controller);
}
Related