使用Visual Studio 2012 RC在MVC 4 / Razor中创建可移植类库?

40
自从使用Visual Studio 2012 RC以来,当在Razor视图中使用可移植类库(.net 4.5和Metro配置文件)时,我们会遇到HttpCompileException异常。
异常信息:(已由谷歌翻译自德语至英语,抱歉)
System.Web.HttpCompileException (0x80004005):     
c:\Users\user\AppData\Local\Temp\Temporary ASP.NET        
Files\root\1995167a\126b7c4d\App_Web_index.cshtml.1fbcdbb1.zaniprm5.0.cs(29):

error CS0012: The type 'System.Object' is not in a referenced assembly is 
defined. Add a reference to the Assembly "System.Runtime, Version = 4.0.0.0, 
Culture = neutral, PublicKeyToken = b03f5f7f11d50a3a" added.   

at
System.Web.Compilation.AssemblyBuilder.Compile()   
System.Web.Compilation.BuildProvidersCompiler.PerformBuild()    
System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath)
...

解决方案结构:
  • 可移植类库(.net 4.5和metro配置文件)
    • public class User { ... }
  • MVC 4(.net 4.5)
    • 引用可移植类库
    • Razor视图
      • @model User
自从Visual Studio 2012 RC以后,不再支持添加“System.Runtime”引用。

1
作为一种解决方法,你能否将便携式类库更改为除.NET 4.5和Metro风格之外还针对Silverlight 5的目标? - Daniel Plaisted
1个回答

60

在 Views\Web.config 文件中,在 <system.web> 部分下添加以下代码:

<compilation debug="true" targetFramework="4.5">
    <assemblies>
        <add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </assemblies>
</compilation>

根据您的可移植代码使用的类型,可能还需要引用一堆其他程序集。 您可以在遇到错误时逐个添加每个程序集,或者将完整的程序集列表添加到C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\Facades中。


2
这个使用 System.Collections.Immutable 解决了我类似的问题。 - aboy021
根据您在项目中的实际需求,您可能还需要将相同的代码行添加到根目录下的 Web.Config 文件中。 - joshcomley
1
@LukePuplett 有点晚了,但这里有一个很好的解释 http://www.lyalin.com/2014/04/25/the-type-system-object-is-defined-in-an-assembly-that-is-not-reference-mvc-pcl-issue/ - Wet Noodles
1
@WetNoodles 谢谢。有趣的是,如果你在博客中跟随链接回到 SO,那就是我的问题。 - Luke Puplett

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接