Razor engine not finding views

2019-08-16 16:47发布

问题:

Issue

I currently have a .NET Core library that I am using to render Razor pages as HTML emails. I am following this tutorial. There are no errors during compile-time but at runtime I am getting the following error:

'Unable to find view '/Views/Emails/NewOrder/NewOrder.cshtml'. The following locations were searched: /Views/Emails/NewOrder/NewOrder.cshtml'

I have set the build action of NewOrder.cshtml to Content and I have set the copy to output directory to Copy Always. I am unsure to why this is unable to find the view as I can see in the bin\Debug\netcoreapp2.2\Views folder that the emails are being copied to the output directory.


Code

I am searching for the view with the following code:

private IView FindView(ActionContext actionContext, string viewName)
{
    var getViewResult = _viewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage: true);
    if (getViewResult.Success)
    {
        return getViewResult.View;
    }

    var findViewResult = _viewEngine.FindView(actionContext, viewName, isMainPage: true);
    if (findViewResult.Success)
    {
        return findViewResult.View;
    }

    var searchedLocations = getViewResult.SearchedLocations.Concat(findViewResult.SearchedLocations);
    var errorMessage = string.Join(
        Environment.NewLine,
        new[] {$"Unable to find view '{viewName}'. The following locations were searched:"}.Concat(
            searchedLocations));

    throw new InvalidOperationException(errorMessage);
}

回答1:

It seemed that it was looking in the source directory instead of the actually executing assembly folder. I fixed it by changing the first line of the FindView method to the following:

var dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var getViewResult = _viewEngine.GetView(executingFilePath: dir, viewPath: viewName, isMainPage: true);