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();
    }
  • 相关阅读:
    手工创建数据库的全部脚本及说明(转)
    HNOI 2009 梦幻布丁 链表 启发式合并
    【除草】【hnoi】精简题解
    矩阵乘法
    忧桑啊。。。
    【水】【SCOI】 精简题解
    [数论][SDOI2012]Longge的问题
    【2013】省选
    【集训队互测】ayq 三道题
    【水】 【SDOI】 极精简题解
  • 原文地址:https://www.cnblogs.com/dudu/p/9060857.html
Copyright © 2011-2022 走看看