Razor页面在运行时无法在ASP

Razor页面在运行时无法在ASP

本文介绍了Razor页面在运行时无法在ASP.NET Core RC2中看到引用的类库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I started a new MVC Web Application project for the RC2 release and I'm trying to add a class library as a project reference.

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

I added a simple class library to my project and referenced it and got the following in the project.json file:

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

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

I can use this library in any of the Controllers and the Startup.cs files without any trouble but I get the following error at run time when I try and use the library from a Razor page:

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

It's weird because I'm getting intellisense for the class library when I'm editing the Razor page, and I can't find anything that says you can't use project references from here.

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

I thought it was hard enough getting this running under RC1 with the "wrap folder" in the class library project but this has me stumped.

推荐答案

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

A workaround has been posted on the issue page (cred to pranavkm and patrikwlund)https://github.com/aspnet/Razor/issues/755

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

Apparently you need to explicitly add references to Razor compilation using RazorViewEngineOptions.CompilationCallback.

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

Add the following to your ConfigureServices method in your Startup class:

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页面在运行时无法在ASP.NET Core RC2中看到引用的类库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:40