我正在尝试 Build 一对.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:找不到视图'Components / Test / Default' . 搜索了以下位置:/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
所以看起来很好 .
2 回答
我设法通过删除基本命名空间来使其工作 .
o.FileProviders.Add(new EmbeddedFileProvider(typeof(TestViewComponent) .GetTypeInfo().Assembly));
似乎添加基本命名空间不能按预期工作 . 不知道为什么
我有这个问题,它通过将
View
上的Build Action
属性从None
更改为Embedded Resource
来解决 .右键单击
Solution Explorer
中的视图 .选择
Properties
.将
Build Action
更改为Embedded Resource
.或者,如果要将所有
Views
自动添加为Embedded Resources
,可以将此ItemGroup
添加到.csproj
文件中:<ItemGroup> <EmbeddedResource Include="Views\**\*.cshtml" /> </ItemGroup>