【发布时间】:2017-03-18 01:44:41
【问题描述】:
我正在尝试设置一对 .NET Core 项目,其中一个是包含 ViewComponent 的类库,另一个是使用该组件的 ASP.NET Core MVC 应用程序。
我按照这里的指南进行操作:http://www.strathweb.com/2016/01/re-using-external-view-components-in-asp-net-5-asp-net-mvc-6/
但是,我似乎无法使其正常工作。我不断得到:
InvalidOperationException:视图“组件/测试/默认”不是 成立。搜索了以下位置: /Views/Home/Components/Test/Default.cshtml /Views/Shared/Components/Test/Default.cshtml
组件本身:
public class TestViewComponent : ViewComponent
{
public TestViewComponent()
{
}
public IViewComponentResult Invoke()
{
return View();
}
}
对应的视图(文件路径为Views/Shared/Components/Test/Default.cshtml):
<p>Hello from test component</p>
来自 ConfigureServices 的相关位告诉 Razor 在程序集中查找视图:
services.Configure<RazorViewEngineOptions>(o =>
{
o.FileProviders.Add(new EmbeddedFileProvider(
typeof(TestViewComponent).GetTypeInfo().Assembly, "Test.Components"));
});
类库项目中的project.json:
"buildOptions": {
"embed": {
"include": [ "Views" ]
}
},
最后,在 MVC 项目中 _Layout.cshtml 的底部:
@await Component.InvokeAsync("Test")
</body>
</html>
我尝试过的事情:
- 将组件的 Default.cshtml 移动到 MVC 项目中的正确位置。这让一切正常,所以我很确定这只是 Razor 找到视图的问题。
- 检查视图是否已正确嵌入到程序集中。我使用了
GetManifestResourceNames(),它被列为MiddlewareTest.Views.Shared.Components.Test.Default.cshtml,所以看起来不错。
【问题讨论】:
标签: asp.net-core-mvc