Sitecore, custom MVC controllers and routes

北战南征 提交于 2019-12-06 02:48:01
Martin English

Here is a working example taken from one of my projects.

Custom Route Registration:

namespace Test.Project.Pipelines.Initialize
{
    public class InitRoutes : Sitecore.Mvc.Pipelines.Loader.InitializeRoutes
    {
        public override void Process(PipelineArgs args)
        {
            RegisterRoutes(RouteTable.Routes);
        }

        protected virtual void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute(
                "Test", // Route name
                "api/test/{controller}/{action}/{id}", // URL with parameters
                 new { id = UrlParameter.Optional }
                );
        }
    }
}

Initialize Pipeline Config:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
     <pipelines>
         <initialize>
            <processor type="Test.Project.Pipelines.Initialize.InitRoutes, Test.Project"
         patch:after="processor[@type='Sitecore.Mvc.Pipelines.Loader.InitializeRoutes, Sitecore.Mvc']" />
        </initialize>
     </pipelines>
  </sitecore>
</configuration>

Here is the code that will create a route for you. In global.asax.cs you will call RegisterRoutes from App_Start event handler:

    protected void Application_Start()
    {
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }

And there you specify your route as:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute(
             name: "test",
             url: "mvc/Forms/{action}/{id}",
             defaults: new { controller = "Forms", action = "Test", id = UrlParameter.Optional }
           );
    }

You will have /mvc/ prefix in this case that will handle your route to specifies controller, so you will call it as:

/mvc/Forms/Test/{you_may_pass_some_optional_GUID_here}

This will route to FormsController class action method Test(string id) but you may omit id parameter

Finally I've got it working correctly. As I wrote TransferRoutedRequest wasn't working as expected, so I had to override it. Still, even if it worked as it's supposed to, the route wasn't being resolved. The problem was in the pipeline configuration. Thanks to a colleague I opened SitecoreRocks pipeline tool and it showed the pipeline was registered in a position too far away from where it should have been, so it was never hit (I had registered it after ItemResolver, as it was on the original configuration). I patched it before LayoutResolver and that did the trick. The route was resolved. Still, Sitecore wasn't able to create an instance of the type, as it was in another assembly. Even specifying the controller's namespace didn't solve the problem. So I had to make some modifications and override CreateController method of ControllerFactory class and override InitializeControllerFactory processor (which I already had modified to be able to work with a DI container), writing a new ControllerFactory and a new SitecoreControllerFactory.

The final code looks like this:

public override IController CreateController(RequestContext requestContext, string controllerName)
    {
        var controller = SC.Context.Item == null || SC.Context.Item.Visualization.Layout == null
                        ? base.GetControllerType(requestContext, controllerName)
                        : TypeHelper.GetType(controllerName);

        return GetControllerInstance(requestContext, controller);
    }

In case I'm dealing with a Sitecore item, I use TypeHelper to return current controller type from a controller rendering or layout. Otherwise I use DefaultControllerFactory.GetControllerType to resolve the custom route.

The only thing to be careful: in case 2 or more namespaces have a controller with the same name and action, it's mandatory to add a namespace in order to identify them.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!