Render a Razor Page to string in ASP.NET Core 2 - NullReferenceException

With inspiration from https://ppolyzos.com/2016/09/09/asp-net-core-render-view-to-string/ I tried to make an service to render Razor pages to a string.

It seems like page.ViewContext.View is empty and results in a nullreferenceexception. How do i fix this?

var result = await _pageRenderService.RenderPageToStringAsync("Index", viewModel);

Open in new window


The service:
   public interface IPageRenderService
    {
        Task<string> RenderPageToStringAsync(string pageName, object model);
    }
 
    public class PageRenderService : IPageRenderService
    {
        private readonly IRazorViewEngine _razorViewEngine;
        private readonly ITempDataProvider _tempDataProvider;
        private readonly IServiceProvider _serviceProvider;
		private readonly IHttpContextAccessor _httpContext;
		private readonly IActionContextAccessor _actionContext;
 
        public PageRenderService(
			IRazorViewEngine razorViewEngine,
            ITempDataProvider tempDataProvider,
            IServiceProvider serviceProvider,
			IHttpContextAccessor httpContext,
			IActionContextAccessor actionContext
			)
        {
            _razorViewEngine = razorViewEngine;
            _tempDataProvider = tempDataProvider;
            _serviceProvider = serviceProvider;
			_httpContext = httpContext;
			_actionContext = actionContext;
        }
 
		public async Task<string> RenderPageToStringAsync(string pageName, object model)
		{
			var tempData = new TempDataDictionary(_httpContext.HttpContext, _tempDataProvider);

			var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
			{
				Model = model
			};

			var actionContext = new ActionContext(
				_httpContext.HttpContext, 
				_httpContext.HttpContext.GetRouteData(), 
				_actionContext.ActionContext.ActionDescriptor
			);

			var page = _razorViewEngine.FindPage(actionContext, pageName).Page;
			if (page == null)
			{
				throw new ArgumentNullException($"Sorry! {pageName} does not match any available page");
			}

			using (var sw = new StringWriter())
            {
				// TODO seemingly the page.ViewContext.View is empty and results in a nullreferenceexception
				page.ViewContext = new ViewContext(
						actionContext,
						page.ViewContext.View, 
						viewDictionary,
						tempData,
						sw,
						new HtmlHelperOptions()
				);
				page.ViewContext.ViewData = viewDictionary;
				await page.ExecuteAsync();
			}
				
			return page.BodyContent.ToString();
			
		}
	}

Open in new window

Ole Kristian LosvikAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.