【问题标题】:RazorEngine - Namespace import compilation errorRazorEngine - 命名空间导入编译错误
【发布时间】:2011-08-26 09:31:43
【问题描述】:

我在非 MVC 环境中使用 Razor 引擎 (razorengine.codeplex.com)。我编译存储在文件中的模板并使用@inherits 来支持智能感知。

  • RazorEngine 组件
  • 自定义程序集 - 引用 RazorEngine,包含 View<> 并将 View<> 设置为基类
  • Web 应用程序 - 引用 RazorEngine、自定义程序集,包含 .cshtml 模板文件

所有 cshtml 文件都有以下 @inherits 指令:

@inherits View<SomeModel>

抛出一个错误:

没有找到命名空间视图的类型,是否缺少程序集引用?

我的 web.config 包含以下条目:

<add namespace="CustomAssembly.NamespaceContainingViewClass" />

我认为这与另一个条目&lt;assemblies&gt; 有关,其中没有提到我的CustomAssembly。是这样吗?我可以使用包含在另一个程序集中的自定义基类进行编译吗?

附言我无法检索程序集的强名称,因为我的自定义程序集引用了一个也没有强名称的 3d 方程序集...

堆栈跟踪:

at RazorEngine.Compilation.DirectCompilerServiceBase.CompileType(TypeContext context)
at RazorEngine.Templating.TemplateService.CreateTemplate(String template, Type modelType)
at RazorEngine.Templating.TemplateService.GetTemplate(String template, Type modelType, String name)
at RazorEngine.Templating.TemplateService.Compile(String template, Type modelType, String name)
at RazorEngine.Razor.Compile(String template, Type modelType, String name)

【问题讨论】:

  • 这个错误在哪里抛出?堆栈跟踪是什么?
  • 当我使用参数调用Razor.Compile 时抛出错误(其中一个是包含@inherits 的模板字符串)。我已将堆栈跟踪添加到上面的问题中。
  • 当您在@inherits 之后有完全限定名称时是否有效。可能是 MVC 做了一些额外的工作来让命名空间工作。您是否也尝试使用 @using MyNamespace 在模板本身中添加命名空间;
  • 是的,它确实适用于全名。我个人认为还需要提供&lt;assemblies&gt; 条目,但是由于命名很严格,这是不可能的。我没有可提供的 publickeytoken...

标签: .net razor razorengine


【解决方案1】:

您可以在 TemplateServiceConfiguration 中添加命名空间:

    TemplateServiceConfiguration templateConfig = new TemplateServiceConfiguration();
    templateConfig.Namespaces.Add("MyNamespaceGoesHere"); 
    templateConfig.Resolver = new DelegateTemplateResolver(name =>
    {
       <My template resolve implementation>
    }
    Razor.SetTemplateService(new TemplateService(templateConfig));
    using (TextWriter tw = new StringWriter())
    {
      Razor.Resolve(viewName + ".cshtml", model).Run(new ExecuteContext(), tw);
      var emailHtmlBody = tw.ToString();
    }

【讨论】:

    【解决方案2】:

    您可能需要将 razor 配置部分添加到您的 web.config

    <?xml version="1.0" encoding="UTF-8" ?>
    <configuration>
        <configSections>
            <section name="razorEngine" type="RazorEngine.Configuration.RazorEngineConfigurationSection, RazorEngine" requirePermission="false" />
        </configSections>
    </configuration>
    
    <razorEngine>
        <namespaces>
            <add namespace="CustomAssembly.NamespaceContainingViewClass" />
        </namespaces>
    </razorEngine>
    

    【讨论】:

    • 我将它添加到包含视图的文件夹中:/layout/razor_views/web.config 没有任何成功...
    • 应该在主web.configapp.config
    • 这个项目早就经历了很多变化。请看github项目github.com/Antaris/RazorEngine
    猜你喜欢
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 2012-07-19
    • 2011-12-24
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多