你基本上走在正确的轨道上。 ASP.NET Core 摆脱了许多静态对象,因此您无法执行以下操作Resolver.GetService
. Resolver
不存在。相反,使用依赖注入 https://docs.asp.net/en/latest/fundamentals/dependency-injection.html system.
如果您只需要访问ICompositeViewEngine
从控制器中将其注入构造函数中:
public MyController(ICompositeViewEngine viewEngine)
{
// save a reference to viewEngine
}
如果您想要一个处理 Razor 到字符串渲染的离散服务,您需要在启动时注册它:
public void ConfigureServices(IServiceCollection services)
{
// (Other code...)
services.AddTransient<IViewRenderingService, ViewRenderingService>();
services.AddMvc();
}
服务本身看起来像这样:
using System;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
public interface IViewRenderingService
{
string RenderPartialView(ActionContext context, string name, object model = null);
}
public class ViewRenderingService : IViewRenderingService
{
private readonly ICompositeViewEngine _viewEngine;
private readonly ITempDataProvider _tempDataProvider;
public ViewRenderingService(ICompositeViewEngine viewEngine, ITempDataProvider tempDataProvider)
{
_viewEngine = viewEngine;
_tempDataProvider = tempDataProvider;
}
public string RenderPartialView(ActionContext context, string name, object model)
{
var viewEngineResult = _viewEngine.FindView(context, name, false);
if (!viewEngineResult.Success)
{
throw new InvalidOperationException(string.Format("Couldn't find view '{0}'", name));
}
var view = viewEngineResult.View;
using (var output = new StringWriter())
{
var viewContext = new ViewContext(
context,
view,
new ViewDataDictionary(
new EmptyModelMetadataProvider(),
new ModelStateDictionary())
{
Model = model
},
new TempDataDictionary(
context.HttpContext,
_tempDataProvider),
output,
new HtmlHelperOptions());
view.RenderAsync(viewContext).GetAwaiter().GetResult();
return output.ToString();
}
}
}
要从控制器使用它,请注入并调用它:
public class HomeController : Controller
{
private readonly IViewRenderingService _viewRenderingService;
public HomeController(IViewRenderingService viewRenderingService)
{
_viewRenderingService = viewRenderingService;
}
public IActionResult Index()
{
var result = _viewRenderingService.RenderPartialView(ControllerContext, "PartialViewName", model: null);
// do something with the string
return View();
}
}
如果您想完全在 MVC 之外使用 Razor,请参阅这个答案 https://stackoverflow.com/a/38253402/3191599.