剃刀引擎找不到视图

时间:2019-03-08 19:57:26

标签: c# asp.net-core razor

问题

我目前有一个.NET Core库,用于将Razor页面呈现为HTML电子邮件。我正在关注this tutorial。编译时没有错误,但在运行时出现以下错误:

  

“无法找到视图” /Views/Emails/NewOrder/NewOrder.cshtml”。的   搜索了以下位置:   /Views/Emails/NewOrder/NewOrder.cshtml'

我已将NewOrder.cshtml的构建动作设置为Content,并且将复制到输出目录的副本设置为Copy Always。我不确定为什么无法找到视图,正如我在bin\Debug\netcoreapp2.2\Views文件夹中看到的那样,将电子邮件复制到了输出目录。


代码

我正在使用以下代码搜索视图:

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 个答案:

答案 0 :(得分:0)

似乎在查找源目录,而不是实际执行的程序集文件夹。我通过将FindView方法的第一行更改为以下内容来修复了该问题:

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