问题
我目前有一个.NET核心库,我用来将其作为HTML电子邮件呈现剃须刀页面。我正在关注本教程。编译时间没有错误,但是在运行时我会收到以下错误:
'无法找到视图'/views/emails/neworder/neworder.cshtml'。这 搜索以下位置: /views/emails/neworder/neworder.cshtml'
我已经将NewOrder.cshtml
的构建动作设置为Content
,并且将副本设置为Copy Always
输出目录。我不确定为什么在binDebugnetcoreapp2.2Views
文件夹中看到的那样,为什么将电子邮件复制到输出目录中。
代码
我正在使用以下代码搜索视图:
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);
}
似乎是在源目录中查看而不是实际执行的汇编文件夹。我通过将FindView
方法的第一行更改为以下内容来修复:
var dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var getViewResult = _viewEngine.GetView(executingFilePath: dir, viewPath: viewName, isMainPage: true);
tachyon的答案对我有用。这是我拥有的代码:
var dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
dir = Path.Combine(dir, "Templates");
var viewResult = _razorViewEngine.GetView(dir, "Index.cshtml", true);
请注意,我必须设置" index.cshtml"。文件为"如果更新"