ASP.NET Core 2.1 中 ViewResultExecutor 的变化
之前在 ASP.NET Core 2.0 中可以正常运行的代码:
var services = HttpContext.RequestServices; var executor = services.GetRequiredService<ViewResultExecutor>(); var viewEngine = services.GetRequiredService<IRazorViewEngine>(); var view = viewEngine.GetView(null, "~/Pages/IeAlert.cshtml", true)?.View; if (view != null) { using (view as IDisposable) { await executor.ExecuteAsync(ControllerContext, view, ViewData, TempData, "text/html; charset=utf-8", 200); } return new EmptyResult(); }
升级到 ASP.NET Core 2.1 之后出现下面的错误:
System.InvalidOperationException: No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor' has been registered. at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
查看 ViewResultExecutor 的定义发现 ViewResultExecutor 实现了 IActionResultExecutor<ViewResult> 接口,查看最新的 ASP.NET Core MVC 的源代码发现这样的注册:
services.TryAddSingleton<IActionResultExecutor<ViewResult>, ViewResultExecutor>();
原来 ViewResultExecutor 也被抽象了,于是改为下面的代码解决了问题:
var services = HttpContext.RequestServices; var executor = services.GetRequiredService<IActionResultExecutor<ViewResult>>() as ViewResultExecutor ?? throw new ArgumentNullException("executor"); var viewEngine = services.GetRequiredService<IRazorViewEngine>(); var view = viewEngine.GetView(null, "~/Pages/IeAlert.cshtml", true)?.View; if (view != null) { using (view as IDisposable) { await executor.ExecuteAsync(ControllerContext, view, ViewData, TempData, "text/html; charset=utf-8", 200); } return new EmptyResult(); }