Razor engine cant find view

2020-04-04 02:36发布

问题:

Im trying to render a html from a view without using a web request. I need the HTML as a string, internally, i do not wish to serve it.

The viewEngine.FindView() returns a viewEnineResult that shows no view was found. It shows to search locations where it looked they look like this:

/Views//PDFOperationsReportView.cshtml

/Views/Shared/PDFOperationsReportView.cshtml

(Observe the double forward slash in the first line)

File structure (I placed it into a HTML snippet cause i couldnt manage to format the text properly in this editor)

Project 
  Folder 
    Subfolder
        CodeFile.cs
  Views
    PDFOperationsReportView.cshtml

The code:

   var viewName = "PDFOperationsReportView";
        var actionContext = GetActionContext();
        var viewEngineResult = _viewEngine.FindView(actionContext, viewName, false);
        if (!viewEngineResult.Success)
        {
            throw new InvalidOperationException(string.Format("Couldn't find view '{0}'", viewName));
        }

        var view = viewEngineResult.View;

回答1:

I had the same issue. I found the answer here: GitHub aspnet/Mvc Issue #4936

Basically, use GetView instead of FindView, like this:

var viewResult = razorViewEngine.GetView(viewName, viewName, false);