首页 > 解决方案 > 使用 RazorEngine 在 `cshtml` 中使用外部 CSS

问题描述

我想在我的cshtml文件中使用外部和内部 CSS。

我在这里使用RazorEngine编译器。

如果我尝试在不添加外部 CSS 的情况下运行,它工作正常。但是当我尝试添加外部 CSS 时,它会抛出下面提到的错误:

RazorEngine.Templating.TemplateCompilationException: '编译模板时出错。请尝试以下方法来解决这种情况: * 如果问题与缺少/无效引用或多个定义有关,请尝试手动加载缺少的引用(在编译的 appdomain 中!)或通过提供您自己的 IReferenceResolver 实现来手动指定您的引用。请参阅https://antaris.github.io/RazorEngine/ReferenceResolver.html详情。目前,所有参考资料都必须以文件形式提供!* 如果你得到'class'不包含'member'的定义:尝试另一个modelType(例如'null'使模型动态)。注意:您不能使用 typeof(dynamic) 使模型动态化!或者尝试使用静态而不是匿名/动态类型。有关错误的更多详细信息:-错误:(17、29)名称'Url'在当前上下文中不存在编译的临时文件可以在(请删除文件夹)中找到:C:\Users\pratik.soni \AppData\Local\Temp\RazorEngine_d253hedw.3b5 我们尝试编译的模板是: ------------- START ----------- @model DRC.DTO.EFiling .NewEFilingDeclarationModel;

CSHTML 文件如下:

@model DRC.DTO.EFiling.NewEFilingDeclarationModel;
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=\, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="@Url.Content("~/wwwroot/CSS/StyleSheet.css")" rel="stylesheet" />
</head>
<body class="bg-gray">
    <h2 class="h2">VAT e-Filing</h2>
    <div class="bg-white">
        <div class="">

. . .

编译模板的代码如下:

public string CompileTemplate(string templatePath, string name, object model)
        {
            string rootPath = _env.ContentRootPath;
            string fullPath = Path.Combine(rootPath, templatePath, name).ToString();
            string templateSource = File.ReadAllText(fullPath);

            string templateString;
            if (Engine.Razor.IsTemplateCached(name, model.GetType()))
            {
                templateString = Engine.Razor.Run(name, model.GetType(), model);
            }
            else
            {
                templateString = Engine.Razor.RunCompile(templateSource, name, model.GetType(), model); //**GETTING ERROR ON THIS LINE**
            }

            return templateString;
        }

样式表.css

body {
}

.h2 {
    color: blue;
    margin-left: 20px;
}

标签: cssrazorasp.net-core-2.0razorengine

解决方案


UrlHelper仅存在于请求的上下文中。您正在请求管道之外呈现视图,因此Url未定义。但是,无论如何,您实际上并不需要它。您应该能够将代码更改为:

<link href="~/wwwroot/CSS/StyleSheet.css" rel="stylesheet" />

推荐阅读