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?

Improve company productivity with a Business Account.Sign Up

x
All Courses

From novice to tech pro — start learning today.