I'm trying to generate a PDF from HTML and I have a method that uses the RenderAsync method, it works with ASP.NET Core 2.1, but I need to use ASP.NET Core 3.0 in my project, but when I updated it to ASP.NET Core 3.0, RenderAsync failed and threw:

object reference not set to an instance of an object

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 Answers