In this tutorial, you will learn how to set-up and use a normal vanilla MVC controller within Umbraco CMS. Out-of-the-box, a vanilla MVC controller will not work with Umbraco. A few extra configurations will be required first. Read on to learn what these are. There are many reasons why you may want to create a normal MVC controller rather than using a Umbraco route-hijacked controller. For example, you may want to create a vanilla MVC controller when you are building the header and footer. Rendering the header and footer using a dedicated controller will allow you to add additional caching which will improve performance.
The code to render a normal controller is the same as you would find in a normal MVC website:
The default action in this controller would try to load a file called 'Header.cshtml' within the 'View' folder, inside of a sub-folder called 'Partials'. This code is very simple to understand but in its current form, it will not work. The big issue that you will encounter when trying to get a vanilla MVC controller like this to work in Umbraco is the routing. In a normal MVC website, a URL is mapped to a controller and an action. In a CMS, the URL is mapped to a virtual page that lives in a database. The routing in a normal MVC controller is configured to match the controllers and actions defined within a project. In Umbraco, the default routing is configured to map URL to pages within the content-tree. If you tried to access a vanilla controller in Umbraco by using the controller and action names alone, you would encounter a 404 error. This is because of this default routing rule. To prevent this error from occurring, you will need to register a custom route within the routing table that will map a controller to a URL. Within Umbraco V8 this is done using a composer and a component. The component to register a route within the routing table looks like this:
A component on its own will do nothing. To ensure Umbraco processes your component, you will need to register it within a custom composer, like this:
With the composer and component installed and compiling correctly, your custom vanilla MVC controller will now load. Happy coding!