首页 文章

从RazorClassLibrary渲染RazorPage到字符串失败渲染部分

提问于
浏览
0

在ASP.NET Core 2.2中渲染RazorPage时工作完全正常,直到我添加一个部分标记,当我在浏览器中打开它时工作正常,但是当我使用RazorPageToStringRenderer调用它时出现以下错误:

InvalidOperationException: The partial view '_EmailButton' was not found. The following locations were searched:
/Views/Home/_EmailButton.cshtml
/Views/Shared/_EmailButton.cshtml
/Pages/Shared/_EmailButton.cshtml

这是我的RazorPageToStringRenderer:

public async Task<string> RenderToStringAsync<T>(string pageName, T model) where T : PageModel
{
    var context = new ActionContext(
        httpContext.HttpContext,
        httpContext.HttpContext.GetRouteData(),
        actionContext.ActionContext.ActionDescriptor
    );

    using (var sw = new StringWriter())
    {
        var result = razorViewEngine.GetPage(null, pageName);

        if (result.Page == null)
            throw new ArgumentNullException($"The page {pageName} cannot be found.");

        var view = new RazorView(razorViewEngine,
            activator,
            new List<IRazorPage>(),
            result.Page,
            HtmlEncoder.Default,
            new DiagnosticListener("ViewRenderService"));

        var viewContext = new ViewContext(
            context,
            view,
            new ViewDataDictionary<T>(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            {
                Model = model
            },
            new TempDataDictionary(
                httpContext.HttpContext,
                tempDataProvider
            ),
            sw,
            new HtmlHelperOptions()
        );
        viewContext.ExecutingFilePath = pageName;

        var page = (Page) result.Page;

        page.PageContext = new PageContext
        {
            ViewData = viewContext.ViewData
        };
        page.ViewContext = viewContext;

        activator.Activate(page, viewContext);
        await page.ExecuteAsync();

        return sw.ToString();
    }
}

问题的关键部分是我的RazorPage位于RazorClassLibrary中,它的路径是Areas / Email / Pages / ConfirmEmail.cshtml . 我也有一个ViewImports.cshtml,但我不认为它正确加载它 .

我已经尝试设置ViewContext的ExecutingFilePath属性,但没有任何区别 .

事实:页面:RCL \ Areas \ Email \ Pages \ ConfirmEmail.cshtml我使用以下行渲染部分页面:

<partial name="_EmailButton" model="Model.ButtonModel"/>

部分:RCL \ Areas \ Email \ Pages \ Shared_EmailButton.cshtml

我推出了一个样本项目,在这里重现了这个问题:https://github.com/paulcsiki/TestRCLToString .

1 回答

  • 0

    一种可行的解决方法是使用RCL \ Areas \ Email \ Pages \ ConfirmEmail.cshtml中部分页面的完整路径 .

    从:

    <partial name="_EmailButton" model="Model.ButtonModel"/>
    

    至:

    <partial name="/Areas/Email/Pages/Shared/_EmailButton.cshtml" model="Model.ButtonModel"/>
    

相关问题