Skip to content

Instantly share code, notes, and snippets.

@EdgarValfogo
Created September 26, 2019 20:32
Show Gist options
  • Save EdgarValfogo/d9ea661eb8d0abff7a893fe0a6be9bda to your computer and use it in GitHub Desktop.
Save EdgarValfogo/d9ea661eb8d0abff7a893fe0a6be9bda to your computer and use it in GitHub Desktop.
Asp.net Core service to read Rendered Razor View as string
public class DocumentsController
{
private readonly IViewRenderService _viewRenderService;
// Dependency Injection is happening here
public DocumentsController(IViewRenderService viewRenderService)
{
_viewRenderService = viewRenderService;
}
// .... Methods and more Methods
[HttpGet("generate")]
[AllowAnonymous]
public async Task<IActionResult> Generate()
{
try
{
// ...
string result = await _viewRenderService.RenderToStringAsync("SignatureEvents", usersModel);
// ... Results
}
catch (Exception e)
{
throw e;
}
}
}
public void ConfigureServices(IServiceCollection services)
{
// ...
// Adding the service in startup.cs, we add the capability to add this class as Dependency Injection
services.AddScoped<IViewRenderService, ViewRenderService>();
// ...
}
public interface IViewRenderService
{
Task<string> RenderToStringAsync(string viewName, object model);
}
public class ViewRenderService : IViewRenderService
{
private readonly IRazorViewEngine _razorViewEngine;
private readonly ITempDataProvider _tempDataProvider;
private readonly IServiceProvider _serviceProvider;
public ViewRenderService(IRazorViewEngine razorViewEngine,
ITempDataProvider tempDataProvider,
IServiceProvider serviceProvider)
{
_razorViewEngine = razorViewEngine;
_tempDataProvider = tempDataProvider;
_serviceProvider = serviceProvider;
}
public async Task<string> RenderToStringAsync(string viewName, object model)
{
var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };
var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
using (var sw = new StringWriter())
{
var viewResult = _razorViewEngine.FindView(actionContext, viewName, false);
if (viewResult.View == null)
{
throw new ArgumentNullException($"{viewName} does not match any available view");
}
var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
{
Model = model
};
var viewContext = new ViewContext(
actionContext,
viewResult.View,
viewDictionary,
new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
sw,
new HtmlHelperOptions()
);
await viewResult.View.RenderAsync(viewContext);
return sw.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment