in ASP.NET

InvalidCastException after upgrading from ASP.NET MVC 3 to ASP.NET MVC 4

I have recently upgraded a MVC 3 application to MVC 4 but along the way en-counted some issues around upgrading references in the project.

Specially, I got this error.

1
2
3
4
5
6
7
8
9
System.InvalidCastException was unhandled by user code
Message=[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=1.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_1.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll'.
Type B 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'.
Source=System.Web.WebPages.Razor

Sources on the interweb say that you should change the webpages element back to 1.0.0.0 from 2.0.0.0 in your web config:

1
2
3
<appSettings>
  <add key="webpages:Version" value="1.0.0.0"/>
</appSettings>

but this seems a bit strange having to specify a old version to use the new version of System.Mvc.WebPages?

I believe the better solution is to add a binding redirect to tell any reference that has been using System.Mvc.WebPages 1.0.0.0 to use 2.0.0.0.

the following goes into your web.config

1
2
3
4
5
6
7
8
9
10
 <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
   
      <dependentAssembly>
          <assemblyIdentity name="System.Web.WebPages.Razor"
              publicKeyToken="31bf3856ad364e35" />
          <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>