我需要将Razor页面部分渲染为字符串.
我想创建一个控制器操作,该操作使用包含部分视图和其他可选参数的JSON进行响应.
我熟悉以下将View呈现为字符串的示例:https://github.com/aspnet/Entropy/blob/dev/samples/Mvc.RenderViewToString/RazorViewToStringRenderer.cs
但是,它与Pages不兼容,因为它只在Views目录中搜索,所以即使我给它一个绝对的路径,它试图找到我的_Layout.cshtml(它甚至不应该这样做!)并失败找到它.
我试图修改它以便渲染页面,但是在尝试渲染时,我最终在部分中获得了ViewData的NullReferenceException.我怀疑它与NullView有关,但我不知道该放在那里(RazorView的构造函数需要许多我不知道如何正确获取的对象).
代码:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0: https://www.apache.org/licenses/LICENSE-2.0
// Modified by OronDF343: Uses pages instead of views.
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Internal;
using Microsoft.AspNetCore.Routing;
namespace TestAspNetCore.Services
{
public class RazorPageToStringRenderer
{
private readonly IRazorViewEngine _viewEngine;
private readonly ITempDataProvider _tempDataProvider;
private …Run Code Online (Sandbox Code Playgroud)