【问题标题】:ASP.NET Core - Razor not checking for view embeded in assemblyASP.NET Core - Razor 不检查嵌入在程序集中的视图
【发布时间】: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


    【解决方案1】:

    我设法通过删除基本命名空间使其正常工作。

    o.FileProviders.Add(new EmbeddedFileProvider(typeof(TestViewComponent) .GetTypeInfo().Assembly));

    添加基本命名空间似乎没有按预期工作。不知道为什么

    【讨论】:

      【解决方案2】:

      我遇到了这个问题,通过将View 上的Build Action 属性从None 更改为Embedded Resource 解决了这个问题。

      1. Solution Explorer中右键查看。
      2. 选择Properties
      3. Build Action 更改为Embedded Resource

      或者,如果您想将所有Views 自动添加为Embedded Resources,您可以将此ItemGroup 添加到您的.csproj 文件中:

      <ItemGroup> <EmbeddedResource Include="Views\**\*.cshtml" /> </ItemGroup>

      【讨论】:

      • 在创建具有单个字符串条目的资源文件之前,我遇到了视图没有嵌入的问题。您还可以直接在控制器操作中调用标准视图,而不是使用中间 ViewComponent。
      猜你喜欢
      • 1970-01-01
      • 2021-09-05
      • 2019-06-21
      • 2016-12-01
      • 2018-02-24
      • 1970-01-01
      • 1970-01-01
      • 2018-06-11
      • 2021-08-19
      相关资源
      最近更新 更多