If you have installed Umbraco via Nuget, it is likely that the sites global.asax might not be set-up correctly. If you want to trigger some custom code on application start-up and your global.ascx is never being hit, then read on! In today's guide, I'm going to cover how to enable it in a few simple steps. In case you don't know how to install Umbraco, then I suggest you read this article, Installing Umbraco 7 In Visual Studio Via Nuget
If you open the global.ascx file (not the code behind), you should see this:
This is telling IIS to bypass your global.ascx.cs file(the code-behind) and use the Umbraco Global.ascx code behind, that is located within UmbracoApplication. If we want to add our own custom logic into the start-up, then we need it to point to the file in the webroot. You can do this by changing the following properties:
Add the Codebehind property and point it to the physical path to Global.asax.cs. In the Inherits section, use your site's name and namespace to point to the file. I called my website 'SampleSite' so my global.ascx should look like this:
It's Not Working The Same As I'm Used To!
On a standard MVC web project the default global.ascx might look something similar to this:
The first thing we should cover; Umbraco has different overload. When you want the code to be hit on website launch, you need to override, OnApplicationStarted(). The second thing you need to understand is to remove this line ' RouteConfig.RegisterRoutes(RouteTable.Routes);', why?
Routing in an MVC application like Umbraco differs greatly than a normal website. In a normal website build, when you browse a site in your web browser, the Url used will be used to call a matching controller. If you have a LandingController and type in www.website.com/landing that controller will be hit, simple.
In Umbraco we deal with virtual pages, the Url www.website.com/landing won't map to a direct controller, instead it will map to some document type with a matching name within in the Umbraco database. To ensure the page gets rendered, Umbraco overrides the Global.ascx, adds in its own handlers to find the matching Umbraco document type and then returns that result to a controller.
Within Umbraco controller match document type names, not Url paths. By default your global.ascx will have this line included:
This line is telling the site to ignore Umbraco routing and use default MVC routing. (If you find that your Umbraco controllers are never being hit after making the change above, check this :) Now we know about the differences between a standard MVC global.ascx and an Umbraco global,ascx, our code should look something like this: