【问题标题】:.NET Core 2.2 Render cshtml as string.NET Core 2.2 将 cshtml 呈现为字符串
【发布时间】:2019-03-28 13:53:22
【问题描述】:

我在这个路径中有这个 cshtml 文件

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

我正在尝试将其呈现为字符串并将视图模型传递给它。

目前我正在使用 Nuget 的 RazorLight v1.1.0,这是我迄今为止尝试过的:

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

但是,当我运行它时,我收到一条错误消息,提示我需要一个绝对路径。如何将我当前拥有的内容转换为绝对路径?如果我给它一个绝对路径,当我编译运行程序时,绝对路径不会消失吗?

【问题讨论】:

    标签: c# asp.net-core razor asp.net-core-mvc


    【解决方案1】:

    注入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);
    
            ...
        }
    }
    

    【讨论】:

    • 嗨!谢谢回答。当我发布应用程序时它也有效吗?这就是我所担心的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多