如何在ASP.NET vNext MVC 6(beta1)项目之间共享视图?

时间:2014-12-07 13:58:41

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

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

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

2 个答案:

答案 0 :(得分:3)

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

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

  2. 您需要创建一个IFileSystem来查看这些资源,而不是查看磁盘。这是棘手的部分。我把它放在pastbin上以获得可靠性:http://pastebin.com/aNfq5hNi

  3. 您需要在Startup.cs中注册此IFileSystem:

  4. //... 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。

答案 1 :(得分: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);
        });