我创建了一个 ASP.NET Core MVC (.net core 8) 项目。我添加了一个虚拟 ViewComponent,每次运行该应用程序时,都会收到以下错误:
处理请求时发生未处理的异常。 InvalidOperationException:未找到视图“Components/Dummy/Default”。搜索了以下位置: /Views/Home/Components/Dummy/Default.cshtml /Views/Shared/Components/Dummy/Default.cshtml
我已经检查了 MicroSoft 文档,也检查了 StackOverflow 等论坛,但没有任何效果。
任何帮助将非常感激。
这是 ViewComponent 类:
public class DummyViewComponent : ViewComponent
{
public DummyViewComponent()
{
}
public async Task<IViewComponentResult> InvokeAsync()
{
await Task.Delay(TimeSpan.FromMilliseconds(1));
return View();
}
}
这是 CSHTML:
<div>
Dummy view component!
</div>
这是在主页(索引)页面中调用它的地方:
@{
ViewData["Title"] = "Overview";
}
@section Styles {
}
@await Component.InvokeAsync("Dummy")
@section Scripts {
}
如您所见,这非常简单 - 我真的看不出问题出在哪里。
提前非常感谢。
你所做的似乎没有错误。以下是您可以尝试的一些潜在原因和解决方案:
默认不启用运行时编译,安装
Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
包并修改Program.cs:
builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
尝试指定查看路径:
public async Task<IViewComponentResult> InvokeAsync()
{
await Task.Delay(TimeSpan.FromMilliseconds(1));
return View("~/Views/Shared/Components/Dummy/Default.cshtml");
}
检查您的观点汇编是否存在任何问题。如果您无法解决此问题,您可以删除除视图组件之外的所有其他 html 代码,然后检查它是否有效。
在 Visual Studio 中右键单击文件 (
Views/Shared/Components/Dummy/Default.cshtml
),选择 Properties
,然后验证 Build Action
设置为 Content。
尝试右键单击该项目,选择
Clean
,然后选择 Rebuild
。完成这两种方法后,再次运行应用程序。