I’m working on converting a project from .NET 472 to .NET8. All this code is for .net 8 web app
I need to render a razor view into html so that I can then convert it to a PDF. I have the code to do this in a central project, and I’m using it in two projects: a Web project (usually returning the razor as View()
) and also a Web API project.
Everything works from the Web API project, but from the Web project I get the following error:
RuntimeBinderException: Cannot perform runtime binding on a null reference
CallSite.Target(Closure , CallSite , object )
AspNetCoreGeneratedDocument.Views_Shared__Layout.<ExecuteAsync>b__18_0() in _Layout.cshtml
+
WhiteLabel whiteLabel = ViewBag.WhiteLabel;
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()
AspNetCoreGeneratedDocument.Views_Shared__Layout.ExecuteAsync()
I’m using these SO answers to help craft this Return View as String in .NET Core . I have tried several other solutions like third party libraries and basically all the methods mentioned there, but none mention this error occurring.
var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
{
Model = model
};
var viewContext = new ViewContext(
actionContext,
viewResult.View,
viewDictionary,
new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
stringWriter,
new HtmlHelperOptions()
);
ViewBag.WhiteLabel = _tenantContext?.Settings?.WhiteLabel;
viewResult.View.RenderAsync(viewContext).GetAwaiter().GetResult();
If I put a breakpoint on that last line, I can verify that my object viewContext.ViewBag.WhiteLabel
has a value. No objects inside of it are null, yet I get this error.
When I render this razor using View()
, everything works, so I know that the project is set up to render this document correctly. It’s only when I try to render to raw HTML that this happens. Why is this giving me a null when it’s not null?