36

パーシャルビューである埋め込みリソースを正常に取得するカスタムVirtualFileおよびVirtualPathProvider実装を作成しました。

ただし、それらをレンダリングしようとすると、次のエラーが発生します。

The view at '~/Succeed.Web/Succeed.Web.Controls.SImporter._SImporter.cshtml' must derive from WebViewPage, or WebViewPage<TModel>.

通常のビュー内で部分ビューをレンダリングすると、次のようになります。

Html.RenderPartial("~/Succeed.Web/Succeed.Web.Controls.SImporter._SImporter.cshtml");

これが部分的な見方ではないと信じる原因は何ですか?

編集:私は、仮想ファイルと仮想ファイルプロバイダーの両方の実装のコードを投稿しました。このコンポーネントを機能させるための解決策を探している人のために。この質問は、質問のタイトルに基づいている人にも役立ちます。

参照用のVirtualFileの実装は次のとおりです。

public class SVirtualFile : VirtualFile
{
    private string m_path;

    public SVirtualFile(string virtualPath)
        : base(virtualPath)
    {
        m_path = VirtualPathUtility.ToAppRelative(virtualPath);
    }

    public override System.IO.Stream Open()
    {
        var parts = m_path.Split('/');
        var assemblyName = parts[1];
        var resourceName = parts[2];

        assemblyName = Path.Combine(HttpRuntime.BinDirectory, assemblyName);
        var assembly = System.Reflection.Assembly.LoadFile(assemblyName + ".dll");

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

VirtualPathProvider:

public class SVirtualPathProvider : VirtualPathProvider
{
    public SVirtualPathProvider() 
    { 

    }

    private bool IsEmbeddedResourcePath(string virtualPath)
    {
        var checkPath = VirtualPathUtility.ToAppRelative(virtualPath);
        return checkPath.StartsWith("~/Succeed.Web/", StringComparison.InvariantCultureIgnoreCase);
    }

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

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

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

そしてもちろん、Application_Start()イベントでプロジェクトのGlobal.asaxファイルにこの新しいプロバイダーを登録することを忘れないでください

System.Web.Hosting.HostingEnvironment.RegisterVirtualPathProvider(new SVirtualPathProvider());
4

3 に答える 3

45

~/Views/web.configこれで、不明な場所からビューを提供しているため、かみそりビューの基本クラスを適用および示すファイルはなくなりました( <pages pageBaseType="System.Web.Mvc.WebViewPage">)。したがって、各埋め込みビューの上部に@inheritsディレクティブを追加して、基本クラスを示すことができます。

@inherits System.Web.Mvc.WebViewPage
@model ...
于 2011-10-12T20:59:44.260 に答える
7

OPの回答をベースとして使用しましたが、少し拡張して、質問に対する回答をソリューションに組み込みました。

これは、ここSOでよく聞かれる質問のようですが、完全な答えは見ていません。そのため、私の実用的なソリューションを共有することが役立つかもしれないと思いました。

データベースからリソースをロードし、それらをデフォルトのキャッシュ(System.Web.Caching.Cache)にキャッシュします。

最終的に行ったのは、リソースの検索に使用しているKEYにカスタムCacheDependencyを作成することでした。そうすれば、他のコードが(編集などで)そのキャッシュを無効にするたびに、そのキーへのキャッシュの依存関係が削除され、VirtualPathProviderがそのキャッシュを無効にして、VirtualFileが再ロードされます。

また、データベースリソースに保存する必要がないように、inheritsステートメントを自動的に追加するようにコードを変更しました。また、この「ビュー」は通常のチャネルを介して読み込まれないため、いくつかのデフォルトのusingステートメントを自動的に追加します。 web.configまたはviewstartにデフォルトで含まれているものはすべて使用できません。

CustomVirtualFile:

public class CustomVirtualFile : VirtualFile
{
    private readonly string virtualPath;

    public CustomVirtualFile(string virtualPath)
        : base(virtualPath)
    {
        this.virtualPath = VirtualPathUtility.ToAppRelative(virtualPath);
    }

    private static string LoadResource(string resourceKey)
    {
        // Load from your database respository or whatever here...
        // Note that the caching is disabled for this content in the virtual path
        // provider, so you must cache this yourself in your repository.

        // My implementation using my custom service locator that sits on top of
        // Ninject
        var contentRepository = FrameworkHelper.Resolve<IContentRepository>();

        var resource = contentRepository.GetContent(resourceKey);

        if (String.IsNullOrWhiteSpace(resource))
        {
            resource = String.Empty;
        }

        return resource;
    }

    public override Stream Open()
    {
        // Always in format: "~/CMS/{0}.cshtml"
        var key = virtualPath.Replace("~/CMS/", "").Replace(".cshtml", "");

        var resource = LoadResource(key);

        // this automatically appends the inherit and default using statements 
        // ... add any others here you like or append them to your resource.
        resource = String.Format("{0}{1}", "@inherits System.Web.Mvc.WebViewPage<dynamic>\r\n" +
                                           "@using System.Web.Mvc\r\n" +
                                           "@using System.Web.Mvc.Html\r\n", resource);

        return resource.ToStream();
    }
}

CustomVirtualPathProvider:

public class CustomVirtualPathProvider : VirtualPathProvider
{
    private static bool IsCustomContentPath(string virtualPath)
    {
        var checkPath = VirtualPathUtility.ToAppRelative(virtualPath);
        return checkPath.StartsWith("~/CMS/", StringComparison.InvariantCultureIgnoreCase);
    }

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

    public override VirtualFile GetFile(string virtualPath)
    {
        return IsCustomContentPath(virtualPath) ? new CustomVirtualFile(virtualPath) : base.GetFile(virtualPath);
    }

    public override CacheDependency GetCacheDependency(string virtualPath, IEnumerable virtualPathDependencies, DateTime utcStart)
    {
        if (IsCustomContentPath(virtualPath))
        {
            var key = VirtualPathUtility.ToAppRelative(virtualPath);

            key = key.Replace("~/CMS/", "").Replace(".cshtml", "");

            var cacheKey = String.Format(ContentRepository.ContentCacheKeyFormat, key);

            var dependencyKey = new String[1];
            dependencyKey[0] = string.Format(cacheKey);

            return new CacheDependency(null, dependencyKey);
        }

        return Previous.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
    }

    public override string GetFileHash(string virtualPath, IEnumerable virtualPathDependencies)
    {
        if (IsCustomContentPath(virtualPath))
        {
            return virtualPath;
        }

        return base.GetFileHash(virtualPath, virtualPathDependencies);
    }
}

お役に立てれば!

于 2013-08-04T21:28:32.290 に答える
1

プロジェクト間でMVCコンポーネントを共有するための単純なプロトタイプを作成するために、OPの情報とDarinDimitrovの回答に大きく依存しました。それらは非常に役に立ちましたが、@ modelで共有ビューを使用するなど、プロトタイプで対処されるいくつかの追加の障壁に遭遇しました。

于 2015-03-18T16:10:09.080 に答える