razor - Razor页面在运行时无法在ASP.NET Core RC2中看到引用的类库

标签 razor asp.net-core asp.net-core-mvc

我为RC2版本启动了一个新的MVC Web应用程序项目,并且试图添加一个类库作为项目引用。

我向项目添加了一个简单的类库,并对其进行了引用,并在project.json文件中获得了以下内容:

"frameworks": {
  "net452": {
    "dependencies": {
      "MyClassLibrary": {
        "target": "project"
      }
    }
  }
},


我可以在任何Controllers和Startup.cs文件中使用此库,而不会遇到任何麻烦,但是当我尝试从Razor页面使用该库时,在运行时出现以下错误:


名称“ MyClassLibrary”在当前上下文中不存在
Output.WriteLine(MyClassLibrary.MyStaticClass.SomeStaticString);


这很奇怪,因为在编辑Razor页面时我得到了类库的智能感知,并且找不到任何内容说明您不能在此处使用项目引用。

我以为在类库项目中使用“ wrap folder”在RC1下运行它已经很困难了,但这让我很困惑。

最佳答案

解决方法已发布在问题页面上(信条为pranavkm和patrikwlund)
https://github.com/aspnet/Razor/issues/755

显然,您需要使用RazorViewEngineOptions.CompilationCallback显式添加对Razor编译的引用。

将以下内容添加到Startup类中的ConfigureServices方法中:

var myAssemblies = AppDomain.CurrentDomain.GetAssemblies().Select(x => MetadataReference.CreateFromFile(x.Location)).ToList();

services.Configure((RazorViewEngineOptions options) =>
{
    var previous = options.CompilationCallback;
    options.CompilationCallback = (context) =>
    {
        previous?.Invoke(context);

        context.Compilation = context.Compilation.AddReferences(myAssemblies);
    };
});

关于razor - Razor页面在运行时无法在ASP.NET Core RC2中看到引用的类库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37289436/

相关文章:

c# - 我如何在 MVC 中跨我的 View 模型和服务使用基类?

html - 如何强制 Razor 不生成额外的 html 属性

html - Orchard CMS : How to display a Layout Part in a view?

asp.net-mvc - 通过Ext.Net.ComponentLoader调用PartialView

rest - ASP.NET Core 5 路由重定向

c# - 从另一个项目/程序集访问 asp.net core 中的预编译 View

asp.net-core - RemoteIpAddress 始终为空

jquery - 日期在 jquery 中显示不正确

c# - 使用 Kudu 在 Azure 上部署 ASP.NET vNext beta 2

c# - 连接字符串不能为空值