【问题标题】:How to share Views between ASP.NET vNext MVC 6 (beta1) projects?如何在 ASP.NET vNext MVC 6 (beta1) 项目之间共享视图?
【发布时间】:2014-12-07 13:58:40
【问题描述】:

在 MVC5 中,可以使用 Razor Generator (http://razorgenerator.codeplex.com) 等工具在项目之间共享视图 (Razor)。 如何在 vNext 中实现相同的功能?无法立即识别我的视图(包含视图的项目在 project.json 中列为依赖项)。

InvalidOperationException: The partial view '~/Views/Authentication/_LogInForm.cshtml' was not found. The following locations were searched: ~/Views/Authentication/_LogInForm.cshtml

【问题讨论】:

  • 我应该提到它:在源项目中包含“RazorGenerator.Mvc”不再起作用(引用前面有一个“!”)。

标签: asp.net asp.net-mvc razor asp.net-core asp.net-core-mvc


【解决方案1】:

我们终于设法解决了这个问题。虽然不太容易......

  1. 您需要将视图作为资源嵌入到您将依赖的项目中。为此,请将 "resources": [ "**/*.cshtml" ] 添加到其 project.json。

  2. 您需要创建一个 IFileSystem 来查看这些资源,而不是查看磁盘。这是棘手的部分。为了方便起见,我把它放在了 pastbin 上:http://pastebin.com/aNfq5hNi

  3. 你需要在你的 Startup.cs 中注册这个 IFileSystem:

//... public void Configure(IApplicationBuilder app,IHostingEnvironment env,ILoggerFactory loggerfactory) { //Enable use of views in other assemblies IOptions<RazorViewEngineOptions> razorViewEngineOptions=app.ApplicationServices.GetService<IOptions<RazorViewEngineOptions>>(); razorViewEngineOptions.Options.FileSystem=new MVCAsset.EmbeddedExpiringFileInfoCache( razorViewEngineOptions, app.ApplicationServices.GetService<ILibraryManager>() ); //... } //...

注意:这实际上已经过测试并适用于 MVC6 RC1,我没有测试 BETA1。

【讨论】:

  • 您是否已更新此代码以在 MVC6-beta4 上工作?由于库中的重大更改,您发布的某些代码不再有效。
  • 你有 beta 5 版本吗?
  • 有人看过这个最新的 beta 6、7 等吗?
【解决方案2】:

我不确定这是否有助于访问外部程序集中的视图,但要添加可以发现视图的位置,您可以像这样实现 IViewLocationExpander:

public class ViewLocationExpander : IViewLocationExpander
{
    public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
    {
        var locations = new List<string>(viewLocations);

        locations.Add("Views/MyOtherViewLocation/{0}.cshtml");

        return locations;
    }

    public void PopulateValues(ViewLocationExpanderContext context)
    {

    }
}

在您的 Startup.cs ConfigureServices 方法中,添加:

        services.Configure<RazorViewEngineOptions>(options =>
        {
            var expander = new ViewLocationExpander();
            options.ViewLocationExpanders.Add(expander);
        });

【讨论】:

  • 感谢您的回答,即使它没有回答问题。我在上面发布了我自己的问题的有效答案。
  • 是的,您不能使用此解决方案在 Web 根目录之外使用自定义视图位置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-29
  • 1970-01-01
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-29
相关资源
最近更新 更多