gpt4 book ai didi

asp.net-mvc - ASP.NET Core Razor SDK 类库 - 不在区域目录内的区域 View

转载 作者:行者123 更新时间:2023-12-02 04:58:58 25 4
gpt4 key购买 nike

我正在尝试使用新的 Razor SDK 将我的 View 包含在我的类库中,其中每个类库都是一个 MVC 区域。如果我在我的类库中包含具有 Areas 目录的 View ,例如

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

然后就可以正常加载了。但是我不喜欢必须将它们放在 Areas 目录中,理想情况下路径是:

/MyLibrary/Views/Home/Index.cshtml

我猜我必须使用 View 位置扩展器才能实现此目的。但是,我不知道如何为类库中包含的 View 而不是应用程序中的 View 实现此目的。到目前为止我已经想出了:

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. Thefollowing 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) { }
}

关于asp.net-mvc - ASP.NET Core Razor SDK 类库 - 不在区域目录内的区域 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50967430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com