Search code examples
c#razorasp.net-core-webapiviewengine

How To render HTML with CSHTML Template file in razor with enabled static File


Hello I am actually generating a html file from cshtml template for reporting purpose. The issue is when i use cdn link for bootstrap in the cshtml file the html rendered got all the css i designed but when using a local access of bootstrap it the style is not rendered at all its also the same thing when trying to render images from local file. Here is the code for generating the html file:

var httpContex = new DefaultHttpContext
            {
                RequestServices=_serviceProvider
            };
            var actionContext = new ActionContext(httpContex, new RouteData(), new ActionDescriptor());
            await using var outputWriter = new StringWriter();
            var viewResutl = _viewEngine.FindView(actionContext, templateFileName, false);
            var viewDictionnary = new ViewDataDictionary<TViewModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            {
                Model = viewModel
            };
            var tempDataDictionnary = new TempDataDictionary(httpContex, _tempDataProvider);
            if (!viewResutl.Success)
            {
                throw new KeyNotFoundException($"could not render the HTML,because {templateFileName} template does not exist");
            }
            try
            {
                var viewContext = new ViewContext(actionContext, viewResutl.View, viewDictionnary, tempDataDictionnary, outputWriter, new HtmlHelperOptions());
                await viewResutl.View.RenderAsync(viewContext);
                return outputWriter.ToString();
            }
            catch(Exception ex)
            {
                _logger.LogError(ex, "Could not render the HTML because of an error");
                return string.Empty;
            }

Here is part of the cshtml file :

@model XXXXXReporter.ViewModels.XXXXXModel
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>@Model.title</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="~/StaticFiles/bootstrap.min.css"/>
</head>
<body style="min-height:100vh">
    <div class="container-fluid" >
        <div class="row">
            <div class="col">
                <h2 class="text-center">XXXX Advanced Reporting System</h2>
            </div>
            <div class="col">
                <img src="~/XXXXlogo.png" alt="ANY IMAGE" />
            </div>
            
        </div >
        <div class="row border border-info border-2 rounded bg-info" style="margin-top: 200px;">
            <h3 class="text-center text-white">General Availabilty And Sensor Status[PRTG]</h3>
        </div>
        <div class="row " style="margin-top: 200px;">
            <p>Period Time:<span>All Period</span></p>
            <p>Report By:<span>XXXX</span></p>
            <p>Creation Date:<span>@DateTime.Now</span></p>
            
        </div>
        <div class="row" style="margin-top: 430px;">
            
                    @foreach (var elem in Model.panelList)
                    {
                        
                                @Html.Raw(elem)
                         
                    }
               
        
    </div>
</body>
</html>

This line of code <link rel="stylesheet" href="~/StaticFiles/bootstrap.min.css"/> is never generated when the html is rendered (by commenting the cdn link above it) The project is a .net Core Web API i have overiden the use of static file using this code in startup.cs:

app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, @"StaticFiles")),
                RequestPath = "/StaticFiles"
            });

As stated in my previous question bootstrap and css not working with .net core api i think the problem is with the way razor render the html. Is there a way to make it render the static file I pass in the cshtml file?or is there a correct way to generate html from a template using .net core API? Regards,


Solution

  • Thanks for all your answer. It was caused by puppeteersharp who was unable to serve the static file. For the CSS i am using await page.AddStyleTagAsync(new AddTagOptions { Path = "StaticFiles/bootstrap.min.css" }); to inject the css to the page. For the static image I am encoding it to base64 to make it displayable from there.