【问题标题】:How To render HTML with CSHTML Template file in razor with enabled static File如何在启用静态文件的剃须刀中使用 CSHTML 模板文件呈现 HTML
【发布时间】:2021-11-01 20:04:30
【问题描述】:

您好,我实际上是从 cshtml 模板生成一个用于报告目的的 html 文件。 问题是当我在 cshtml 文件中使用 cdn 链接进行引导时,呈现的 html 得到了我设计的所有 css,但是当使用引导程序的本地访问时,样式根本没有呈现,当尝试从本地文件。 下面是生成html文件的代码:

var httpContex = new DefaultHttpContext
            {
                RequestServices=_serviceProvider
            };
            var actionContext = new ActionContext(httpContex, new RouteData(), new ActionDescriptor());
            await using var outputWriter = new StringWriter();
            var viewResutl = _viewEngine.FindView(actionContext, templateFileName, false);
            var viewDictionnary = new ViewDataDictionary<TViewModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            {
                Model = viewModel
            };
            var tempDataDictionnary = new TempDataDictionary(httpContex, _tempDataProvider);
            if (!viewResutl.Success)
            {
                throw new KeyNotFoundException($"could not render the HTML,because {templateFileName} template does not exist");
            }
            try
            {
                var viewContext = new ViewContext(actionContext, viewResutl.View, viewDictionnary, tempDataDictionnary, outputWriter, new HtmlHelperOptions());
                await viewResutl.View.RenderAsync(viewContext);
                return outputWriter.ToString();
            }
            catch(Exception ex)
            {
                _logger.LogError(ex, "Could not render the HTML because of an error");
                return string.Empty;
            }

这是cshtml文件的一部分:

@model XXXXXReporter.ViewModels.XXXXXModel
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>@Model.title</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="~/StaticFiles/bootstrap.min.css"/>
</head>
<body style="min-height:100vh">
    <div class="container-fluid" >
        <div class="row">
            <div class="col">
                <h2 class="text-center">XXXX Advanced Reporting System</h2>
            </div>
            <div class="col">
                <img src="~/XXXXlogo.png" alt="ANY IMAGE" />
            </div>
            
        </div >
        <div class="row border border-info border-2 rounded bg-info" style="margin-top: 200px;">
            <h3 class="text-center text-white">General Availabilty And Sensor Status[PRTG]</h3>
        </div>
        <div class="row " style="margin-top: 200px;">
            <p>Period Time:<span>All Period</span></p>
            <p>Report By:<span>XXXX</span></p>
            <p>Creation Date:<span>@DateTime.Now</span></p>
            
        </div>
        <div class="row" style="margin-top: 430px;">
            
                    @foreach (var elem in Model.panelList)
                    {
                        
                                @Html.Raw(elem)
                         
                    }
               
        
    </div>
</body>
</html>

这行代码&lt;link rel="stylesheet" href="~/StaticFiles/bootstrap.min.css"/&gt;在渲染html时永远不会生成(通过注释上面的cdn链接) 该项目是一个 .net Core Web API,我在 startup.cs 中使用此代码覆盖了静态文件的使用:

app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, @"StaticFiles")),
                RequestPath = "/StaticFiles"
            });

正如我在上一个问题bootstrap and css not working with .net core api 中所述,我认为问题在于剃须刀呈现 html 的方式。 有没有办法让它呈现我在cshtml文件中传递的静态文件?或者有没有正确的方法使用.net核心API从模板生成html? 问候,

【问题讨论】:

  • 你说的is never generated when the html is rendered是不是意味着你用f12查看页面元素时,里面没有&lt;link rel="stylesheet" href="~/StaticFiles/bootstrap.min.css"/&gt;i.stack.imgur.com/cuATA.png
  • 你的意思是你的css文件已经成功设置为html文件,但是样式内容不行?那么,如果css文件已经加载呢?我的意思是这个文件的路径是否正确。在这里,我更改了文件名,因此遇到了 404 错误,这导致样式丢失。 i.stack.imgur.com/QiT2I.png
  • @TinyWang &lt;link rel="stylesheet" href="~/StaticFiles/bootstrap.min.css"/&gt; 在您按 F12 时出现在 HTML 代码中,但是当您在样式选项卡下查看时,那里没有像通常那样的 css。这是我单击一个元素时显示的内容(没有cdn):Imgur,这是使用cdn 显示的内容:Imgur
  • 嗨,谢谢你的努力,根据你的截图,当你使用本地css文件时,似乎没有.bg-info之类的类,但是当使用cdn时,这些css设置是包含。那么您能否创建一个新文件,例如 temp.css 并从 cdn 的响应中复制数据,并将您的 href="~/StaticFiles/bootstrap.min.css" 更改为新创建的文件? i.stack.imgur.com/hUbPb.png
  • 或复制响应并覆盖您本地的~/StaticFiles/bootstrap.min.css 文件。因为我认为您本地的 css 文件可能缺少类。

标签: c# razor asp.net-core-webapi viewengine


【解决方案1】:

感谢您的所有回答。 这是由 puppeteersharp 无法提供静态文件引起的。 对于 CSS,我使用 await page.AddStyleTagAsync(new AddTagOptions { Path = "StaticFiles/bootstrap.min.css" }); 将 css 注入页面。 对于静态图像,我将其编码为 base64 以使其可从那里显示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多