?

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

Posted on 2018-01-13
0
Low Priority
?
38 Views
Last Modified: 2018-01-13
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

0
Comment
Question by:Ole Kristian Losvik
0 Comments

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Join & Write a Comment

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
As many of you are aware about Scanpst.exe utility which is owned by Microsoft itself to repair inaccessible or damaged PST files, but the question is do you really think Scanpst.exe is capable to repair all sorts of PST related corruption issues?
The Relationships Diagram is a good way to get an overall view of what a database is keeping track of. It is also where relationships are defined. A relationship specifies how two tables connect to each other. As you build tables in Microsoft Ac…

578 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question