在ASP.NET Core应用程序中,如果您使用MVC框架并在视图中使用Razor语法,则可能会遇到此错误:“InvalidOperationException: The view 'ViewName' was not found.”。
通常,这是由于MVC框架无法找到要呈现的视图引起的。您可以通过以下两种方式来解决:
在MVC框架中,视图通常放在“Views”目录下。但是,您可以在应用程序中的其他位置放置视图,并使用以下代码告诉MVC要查找它们的位置:
services.AddMvc().AddRazorOptions(options => { options.ViewLocationFormats.Clear(); options.ViewLocationFormats.Add("/MyViews/{1}/{0}" + RazorViewEngine.ViewExtension); });
请注意,这里,您指定了要查找视图的目录,即“MyViews”,并指定了文件扩展名为“.cshtml”。
另一种解决方法是,手动指定视图引擎。您可以在Startup.cs文件中的Configure方法中添加以下代码来实现此目的:
app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: "MyCustomRoute", template: "{MyCustomController}/{MyCustomAction}/{id?}");
// Specify the view engine explicitly
routes.DefaultHandler = new MvcHandler(
ApplicationServices,
app.ApplicationServices.GetRequiredService(),
app.ApplicationServices.GetRequiredService>().Value);
});
在这里,您手动指定了默认处理程序并将其设置为MvcHandler。这将使MVC知道要使用何种视图引擎。
希望这些解决方案能够帮助您在开发ASP.NET Core