zoukankan      html  css  js  c++  java
  • 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();
    }
  • 相关阅读:
    SVG平移和缩放(鼠标滚轮)的实现
    CSS之容器水平垂直居中
    CSS之flex布局
    CSS之鼠标悬停——内容变深/变浅
    CSS之clip-path绘制多边形
    axios
    .Net 反射
    Redis
    .Net Core GRPC报错
    Python 京东云无线宝消息推送
  • 原文地址:https://www.cnblogs.com/dudu/p/9060857.html
Copyright © 2011-2022 走看看