我终于破解了!我一直走错了方向......解决方法是使用
ViewComponent
。但还有些奇怪!
感谢:
解决方案
将PageModel转换为ViewComponent
namespace MyProject.ViewComponents
{
public class MyViewComponent : ViewComponent
{
private readonly MyDbContext _context;
public MyViewComponent(MyDbContext context)
{
_context = context;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var count = await _context.Foos.CountAsync();
var message = $"Server time is { DateTime.Now } and the Foo count is { count }";
return View<string>(message);
}
}
}
视图位于
Pages/Shared/Components/My/Default.cshtml 中。
@model string
<h2>Test</h2>
<p>
@Model
</p>
这项服务
using System;
using System.IO;
using System.Text.Encodings.Web;
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.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
public class RenderViewComponentService
{
private readonly IServiceProvider _serviceProvider;
private readonly ITempDataProvider _tempDataProvider;
private readonly IViewComponentHelper _viewComponentHelper;
public RenderViewComponentService(
IServiceProvider serviceProvider,
ITempDataProvider tempDataProvider,
IViewComponentHelper viewComponentHelper
)
{
_serviceProvider = serviceProvider;
_tempDataProvider = tempDataProvider;
_viewComponentHelper = viewComponentHelper;
}
public async Task<string> RenderViewComponentToStringAsync<TViewComponent>(object args)
where TViewComponent : ViewComponent
{
var viewContext = GetFakeViewContext();
(_viewComponentHelper as IViewContextAware).Contextualize(viewContext);
var htmlContent = await _viewComponentHelper.InvokeAsync<TViewComponent>(args);
using var stringWriter = new StringWriter();
htmlContent.WriteTo(stringWriter, HtmlEncoder.Default);
var html = stringWriter.ToString();
return html;
}
private ViewContext GetFakeViewContext(ActionContext actionContext = null, TextWriter writer = null)
{
actionContext ??= GetFakeActionContext();
var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary());
var tempData = new TempDataDictionary(actionContext.HttpContext, _tempDataProvider);
var viewContext = new ViewContext(
actionContext,
NullView.Instance,
viewData,
tempData,
writer ?? TextWriter.Null,
new HtmlHelperOptions());
return viewContext;
}
private ActionContext GetFakeActionContext()
{
var httpContext = new DefaultHttpContext
{
RequestServices = _serviceProvider,
};
var routeData = new RouteData();
var actionDescriptor = new ActionDescriptor();
return new ActionContext(httpContext, routeData, actionDescriptor);
}
private class NullView : IView
{
public static readonly NullView Instance = new NullView();
public string Path => string.Empty;
public Task RenderAsync(ViewContext context)
{
if (context == null) { throw new ArgumentNullException(nameof(context)); }
return Task.CompletedTask;
}
}
}
使用方法
从 Razor 页面(调试/微调页面)
请注意没有代码后台文件。
@page
@using MyProject.ViewComponents
@await Component.InvokeAsync(typeof(MyViewComponent))
使用RouteData
@page "{id}"
@using MyProject.ViewComponents
@await Component.InvokeAsync(typeof(MyViewComponent), RouteData.Values["id"])
来自控制器
[HttpGet]
public async Task<IActionResult> Get()
{
var html = await _renderViewComponentService
.RenderViewComponentToStringAsync<MyViewComponent>();
return Ok(new { html });
}
使用 FromRoute
[HttpGet("{id}")]
public async Task<IActionResult> Get([FromRoute] int id)
{
var html = await _renderViewComponentService
.RenderViewComponentToStringAsync<MyViewComponent>(id);
return Ok(new { html });
}
奇怪的现象
很不幸,注入的 IViewComponentHelper
无法直接使用。
因此,我们需要做一些非常不直观的 事情 才能使它正常工作。
(_viewComponentHelper as IViewContextAware).Contextualize(viewContext);
这会引起一系列奇怪的事情,比如假的
ActionContext
和
ViewContext
,需要一个
TextWriter
,但它没有被用于任何事情!实际上,整个
ViewContext
根本没有被使用。它只是需要存在 :(
此外,NullView
...由于某种原因,Microsoft.AspNetCore.Mvc.ViewFeatures.NullView
是Internal
,所以我们基本上必须将其复制/粘贴到我们自己的代码中。
也许未来会有所改进。
总之:在我看来,这比使用IRazorViewEngine
更简单,后者几乎出现在每个网络搜索中 :)