简体   繁体   English

.NET Core 2.2 将 cshtml 呈现为字符串

[英].NET Core 2.2 Render cshtml as string

I have this cshtml file located in this path我在这个路径中有这个 cshtml 文件

"~/Areas/Services/Views/Quotations/SpecificForms/PC/PCReceipts.cshtml"

I am trying to render this as a string and pass a viewmodel to it.我试图将其呈现为字符串并将视图模型传递给它。

Currently I am using RazorLight v1.1.0 from Nuget and this is what I have tried so far:目前我正在使用 Nuget 的 RazorLight v1.1.0,这是我迄今为止尝试过的:

var tempatePath = "~/Areas/Services/Views/Quotations/SpecificForms/PC/PCReceipts.cshtml";
IRazorLightEngine engine = EngineFactory.CreatePhysical(templatePath);

However when I run it, I get an error saying that I require an absolute path instead.但是,当我运行它时,我收到一条错误消息,说我需要一个绝对路径。 How can I convert what I have currently to an absolute path?如何将我当前拥有的内容转换为绝对路径? If I give it an absolute path, when I compile and run the program, won't the absolute path disappear?如果我给它一个绝对路径,当我编译和运行程序时,绝对路径不会消失吗?

Inject IHostingEnvironment and use _env.ContentRootPath :注入IHostingEnvironment并使用_env.ContentRootPath

public class FooController : Controller
{
    private readonly IHostingEnvironment _env;

    public FooController(IHostingEnvironment env)
    {
        _env = env;
    }

    public IActionResult FooAction()
    {
        var tempatePath = Path.Combine(_env.ContentRootPath, "Areas/Services/Views/Quotations/SpecificForms/PC/PCReceipts.cshtml");
        IRazorLightEngine engine = EngineFactory.CreatePhysical(templatePath);

        ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM