加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ASP.NET核心Razor SDK类库 – 不在区域目录中的

发布时间:2020-12-16 09:43:59 所属栏目:asp.Net 来源:网络整理
导读:我正在尝试使用新的Razor SDK将我的视图包含在我的类库中,其中每个类库都是MVC区域.如果我在类库中包含带有Areas目录的视图,例如 /MyLibrary/Areas/MyLibrary/Views/Home/Index.cshtml 然后加载很好.但是我不喜欢我必须将它们放在区域目录中,理想情况下路径
我正在尝试使用新的Razor SDK将我的视图包含在我的类库中,其中每个类库都是MVC区域.如果我在类库中包含带有Areas目录的视图,例如

/MyLibrary/Areas/MyLibrary/Views/Home/Index.cshtml

然后加载很好.但是我不喜欢我必须将它们放在区域目录中,理想情况下路径是:

/MyLibrary/Views/Home/Index.cshtml

我猜我必须使用视图位置扩展器来实现这一点.但是我不知道如何为包含在类库中而不在应用程序中的视图实现此目的.到目前为止,我想出了:

public class AreaViewLocationExpander : IViewLocationExpander {
    public virtual IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context,IEnumerable<string> viewLocations) {
        return viewLocations.Concat(new[] {
            "../{2}/Views/{1}/{0}" + RazorViewEngine.ViewExtension
        });
    }

    public virtual void PopulateValues(ViewLocationExpanderContext context) { }
}

这会引发错误:

InvalidOperationException: The view ‘Index’ was not found. The
following locations were searched:

/Areas/MyLibrary/Views/Home/Index.cshtml

/Areas/MyLibrary/Views/Shared/Index.cshtml

/Views/Shared/Index.cshtml

/Pages/Shared/Index.cshtml

/../MyLibrary/Views/Home/Index.cshtml

但我想,即使它在本地工作,它也不会在生产中或者库被打包在NuGet包中.

如果有人能告诉我如何实现这一目标,我将不胜感激.谢谢

解决方法

步骤1

来自@pranavkm GitHub:

The Razor Sdk uses well-known MSBuild metadata to calculate project
relative paths. You may set the Link metadata for a file and Razor
would use that. For instance,adding this to your project file would
update all cshtml files to have a view engine path with the project
name as a prefix:

<Target Name="UpdateTargetPath" BeforeTargets="AssignRazorGenerateTargetPaths">
  <ItemGroup>
    <RazorGenerate Include="@(RazorGenerate)" Link="$(TargetName)%(RazorGenerate.RelativeDir)%(RazorGenerate.FileName)%(RazorGenerate.Extension)" />
  </ItemGroup>
</Target>

This does not work with runtime compilation – i.e. if you were to
apply this to Application.csproj,it’ll work for build time compiled
views,but runtime compiled views would continue to use
/Views/Home/Index.cshtml

第2步

然后,您需要添加以下IViewLocationExpander:

public class AreaViewLocationExpander : IViewLocationExpander {
    public virtual IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context,IEnumerable<string> viewLocations) {
        return viewLocations.Concat(new[] {
            "/{2}/Views/{1}/{0}" + RazorViewEngine.ViewExtension
        });
    }

    public virtual void PopulateValues(ViewLocationExpanderContext context) { }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读