Return View as String in .NET Core 3.0

534 Views Asked by At

I am working on generating HTML to send to a PDF generator and discovered this this question on Stackoverflow. It points to Paris Polyzos and his article. Upon implementing the code in .Net Core 3.0, the following error appears:

Cannot resolve scoped service 'Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers.IViewBufferScope' from root provider.

Has anyone any thought on how to work around this?

1

There are 1 best solutions below

0
On

I had the same problem with you since I needed to render a HTML view to a string. I managed to solve it by using an IServiceScopeFactory. You need to inject an IServiceScopeFactory (for example via the constructor) and then use that one to create a scope with CreateScope() method and then feed the ServiceProvider of that scope to the HttpContext RequestServices property. For example:

class MyRendererService
{
   private readonly IServiceScopeFactory _serviceScopeFactory {get; set;}
   
   public MyRendererService(IServiceScopeFactory serviceScopeFactory)
   {
     _serviceScopeFactory = serviceScopeFactory;
   }

   public void MyRenderingMethod()
   { 
      using (var scope = _serviceScopeFactory.CreateScope())
      {
         
         var httpContext = new DefaultHttpContext() { RequestServices = scope.ServiceProvider };

         // The rest of your Html rendering code here...
      }
      
   }
}

I know that you might have already solved the problem since you asked this more than a month ago, but it might help someone else too.