为什么RenderAsync在ASP.NET Core 2.2中失败但在Core 2.1中起作用?

时间:2019-05-03 12:24:43

标签: c# asp.net-core asp.net-core-2.2

我正在尝试从HTML生成PDF,并且我有一个使用RenderAsync方法的方法,它可以与ASP.NET Core 2.1一起使用,但是我需要在项目中使用ASP.NET Core 3.0 ,但是当我将其更新为ASP.NET Core 3.0时,RenderAsync失败并抛出:

  

对象引用未设置为对象的实例

public async Task<string> Render<TModel>(string executingViewPath, string viewPath, TModel model)
{
    var viewEngineResult = razorEngine.GetView(executingViewPath, viewPath, false);

    if (!viewEngineResult.Success)
    {
        throw new InvalidOperationException($"Couldn't find view {viewPath}");
    }

    var view = viewEngineResult.View;

    using (var output = new StringWriter())
    {
        var viewContext = new ViewContext();
        viewContext.HttpContext = httpContextAccessor.HttpContext;
        viewContext.ViewData = GetViewData(model);
        viewContext.Writer = output;

        // needed to downgrade to asp.net core 2.1, because render async failed in core 2.2
        await view.RenderAsync(viewContext);//error: object reference not set to an instance of an object.

        return output.ToString();
    }
}

0 个答案:

没有答案