How to load views from a Class Library project?

為{幸葍}努か 提交于 2020-01-01 02:44:00

问题


I tried to create a VirtualPathProvider and set the view as an embedded resource.

class AssemblyResourceVirtualFile : VirtualFile
{
    string path;

    public AssemblyResourceVirtualFile(string virtualPath)
        : base(virtualPath)
    {
        path = VirtualPathUtility.ToAppRelative(virtualPath);
    }

    public override System.IO.Stream Open()
    {
        string[] parts = path.Split('/');
        string assemblyName = parts[2];
        string resourceName = parts[3];

        assemblyName = Path.Combine(HttpRuntime.BinDirectory, assemblyName);
        var assembly = Assembly.LoadFile(assemblyName);

        if (assembly != null)
        {
            return assembly.GetManifestResourceStream(resourceName);
        }
        return null;
    }
}

And

public class AssemblyResourceProvider : System.Web.Hosting.VirtualPathProvider
{
    public AssemblyResourceProvider() { }

    private bool IsAppResourcePath(string virtualPath)
    {
        String checkPath = VirtualPathUtility.ToAppRelative(virtualPath);
        return checkPath.StartsWith("~/App_Resource/", StringComparison.InvariantCultureIgnoreCase);
    }

    public override bool FileExists(string virtualPath)
    {
        return (IsAppResourcePath(virtualPath) ||
                base.FileExists(virtualPath));
    }

    public override VirtualFile GetFile(string virtualPath)
    {
        if (IsAppResourcePath(virtualPath))
            return new AssemblyResourceVirtualFile(virtualPath);
        else
            return base.GetFile(virtualPath);
    }

    public override CacheDependency GetCacheDependency(string virtualPath,
        IEnumerable virtualPathDependencies, DateTime utcStart)
    {
        if (IsAppResourcePath(virtualPath))
            return null;
        else
            return base.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
    }
}

My controller

return View("~/App_Resource/Blog.DLL/Blog.Views.Blog.Latest.cshtml");

It does find the view, but I end up getting this error:

... view.cshtml' must derive from WebViewPage, or WebViewPage<TModel>.

When trying to show the partial view using:

@{ Html.RenderAction("Latest", "Blog"); }

Is there a way to fix it?

Or is there an easier way to store views on a DLL?


回答1:


The reason this happens is because you are now serving the razor views from unknown locations the standard ~/views/web.config no longer applies. So you could put a @inherits System.Web.Mvc.WebViewPage inside your custom views but it could be quite a hassle.

You may checkout the following article.



来源:https://stackoverflow.com/questions/5467227/how-to-load-views-from-a-class-library-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!