【问题标题】:Render Razor View Page as string from WebApi Core将 Razor 视图页面呈现为来自 WebApi Core 的字符串
【发布时间】:2019-06-08 05:09:40
【问题描述】:

我的模拟 cshtml 看起来像这样:

@model TaskManager.Models.ViewModels.ProjectRaportViewModel

@{
    var name = Model.Project.Name;

    <h3>@name</h3>
}
<br />
<4h>Hello World!</4h>

我想将该视图(或任何)返回为string,但作为Razor 呈现的html(所以我认为,剃须刀会将C# 的东西更改为html 标签等)。

我有一个controller,看起来像这样:

    [HttpGet("{projectId}")]
    public IActionResult GetRaportFromProject([FromRoute] int projectId)
    {
        var html = this.pdfService.RenderViewToHtml(projectId);
        return this.Content(html, "text/html", Encoding.UTF8);
    }

pdfService 我有这个方法:

    public string RenderViewToHtml(int projectId)
    {
        this.projectService.GetItem(projectId);

        var raportHtml = what to do next?                   
    }

我的问题是,如何在服务类中通过Razorcshtml 渲染为html,然后从WebApi 端点将其作为string 返回?

【问题讨论】:

    标签: c# asp.net-web-api asp.net-core razor asp.net-core-2.1


    【解决方案1】:

    如果你使用 .Net Core,有一个可以轻松安装的 NuGet 包:RazorEngine.NetCore

    文档很好,但这里是简短版本:

    包含库:

        using RazorEngine;
        using RazorEngine.Templating;
    

    获取你的剃须刀 html

            string razorView= "Hello @Model.Name, welcome to RazorEngine!";
    

    如果它在文件中,您可以使用File.ReadAllText

            string razorView = await File.ReadAllTextAsync(filePath);
    

    并编译:

    string result = Engine.Razor.RunCompile(razorView, "templateKey", null, null);
    

    如果你想注入一些对象,在第四个参数中传递它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-02
      • 2020-11-27
      • 2022-01-20
      • 2012-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多