Friday, March 21, 2014

Solving System.InvalidCastException was unhandled by user code Message=[A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast ......

Recently, while upgrading an Asp.Net MVC 4 project someone created to an Asp.Net MVC 5 project, I ran across a great error. The error was this:

It was also bright and red!


Server Error in '/' Application.

[A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to [B]System.Web.WebPages.Razor.Configuration.HostSection. Type A originates from 'System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Razor\v4.0_2.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll'. Type B originates from 'System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\bc28c2e0\1b833c84\assembly\dl3\efd960b2\2bccde4f_7f44cf01\System.Web.WebPages.Razor.dll'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: [A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to [B]System.Web.WebPages.Razor.Configuration.HostSection. Type A originates from 'System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Razor\v4.0_2.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll'. Type B originates from 'System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\bc28c2e0\1b833c84\assembly\dl3\efd960b2\2bccde4f_7f44cf01\System.Web.WebPages.Razor.dll'.

This error made me VERY unhappy.
However, the solution was VERY simple.
I just needed to tell the application which version to use.
Here are the steps I took.


1. Open the web.config file.
2. Scroll until you find the <assemblybinding> tag under <runtime>.
3. Add in the following dependent assembly information for the dll that is causing you problems. In my case, it was as follows:

<dependentAssembly>

<assemblyIdentity name="System.Web.WebPages.Razor" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="2.0.0.0" newVersion="3.0.0.0"/>

</dependentAssembly>

4. Rebuild your project!

That is it! You should now see the fantastic work you have created after you build and Ctrl-F5. For all of you people out there still making projects with MVC 4 - JUST STOP! Back away slowly! MVC 5 is your friend!

Smooches,
Kila Morton