• 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();
    }
  • 相关阅读:
    制作文件的备份
    文件的读写
    文件的打开与关闭
    文件操作介绍
    数据类型转换
    位运算
    进制
    函数使用注意事项
    匿名函数
     递归函数
  • 原文地址:https://www.cnblogs.com/dudu/p/9060857.html
Copyright © 2020-2023  润新知