Asp.net mvc 嵌入式剃须刀视图

Asp.net mvc 嵌入式剃须刀视图,asp.net-mvc,razor,Asp.net Mvc,Razor,最近,我读了一篇文章,作者描述了如何将razor视图编译成单独的库。我想问一下,是否可以在不编译的情况下在库中嵌入视图?然后,添加自定义VirtualPathProvider以读取视图。在“shell”MVC项目的Global.asax应用程序中\u开始注册自定义VirtualPathProvider: HostingEnvironment.RegisterVirtualPathProvider(new CustomVirtualPathProvider()); 实际的实现将比这更复杂,因为您

最近,我读了一篇文章,作者描述了如何将razor视图编译成单独的库。我想问一下,是否可以在不编译的情况下在库中嵌入视图?然后,添加自定义VirtualPathProvider以读取视图。

在“shell”MVC项目的Global.asax应用程序中\u开始注册自定义VirtualPathProvider:

HostingEnvironment.RegisterVirtualPathProvider(new CustomVirtualPathProvider());
实际的实现将比这更复杂,因为您可能会做一些基于接口的、反射的、数据库查找等操作,作为提取元数据的一种手段,但这是一般的想法(假设您有另一个名为“AnotherMvcAssembly”的MVC项目)使用Foo控制器,Index.cshtml视图被标记为嵌入式资源:

public class CustomVirtualPathProvider : VirtualPathProvider {
    public override bool DirectoryExists(string virtualDir) {
        return base.DirectoryExists(virtualDir);
    }

    public override bool FileExists(string virtualPath) {
        if (virtualPath == "/Views/Foo/Index.cshtml") {
            return true;
        }
        else {
            return base.FileExists(virtualPath);
        }
    }

    public override System.Web.Caching.CacheDependency GetCacheDependency(string virtualPath, System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart) {
        if (virtualPath == "/Views/Foo/Index.cshtml") {
            Assembly asm = Assembly.Load("AnotherMvcAssembly");
            return new CacheDependency(asm.Location);
        }
        else {
            return base.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
        }
    }

    public override string GetCacheKey(string virtualPath) {
        return base.GetCacheKey(virtualPath);
    }

    public override VirtualDirectory GetDirectory(string virtualDir) {
        return base.GetDirectory(virtualDir);
    }

    public override VirtualFile GetFile(string virtualPath) {
        if (virtualPath == "/Views/Foo/Index.cshtml") {
            return new CustomVirtualFile(virtualPath);
        }
        else {
            return base.GetFile(virtualPath);
        }
    }
}

public class CustomVirtualFile : VirtualFile {
    public CustomVirtualFile(string virtualPath) : base(virtualPath) { }

    public override System.IO.Stream Open() {
        Assembly asm = Assembly.Load("AnotherMvcAssembly");
        return asm.GetManifestResourceStream("AnotherMvcAssembly.Views.Foo.Index.cshtml");
    }
}

您可以使用my,它可以通过Nuget安装。它可以从引用的程序集加载资源,也可以设置为在开发过程中依赖源文件,这样您就可以更新视图,而无需重新编译。

您的库为我工作。感谢您完成Nuget包的制作。