【问题标题】:Strange behaviour when loading razor view from custom VirtualPathProvider (ASHX Source)从自定义 VirtualPathProvider(ASHX 源)加载剃刀视图时的奇怪行为
【发布时间】:2011-07-16 18:27:29
【问题描述】:

当我通过自定义 VirtualPathProvider 加载数据时出现一些奇怪的行为。 值得一提的是,我正在尝试将此视图用作布局。

public class MyVirtualPathProvider : VirtualPathProvider
{
    public MyVirtualPathProvider()
        : base()
    {

    }

    public override CacheDependency GetCacheDependency(string virtualPath, IEnumerable virtualPathDependencies, DateTime utcStart) 
    {
        if ((virtualPath.StartsWith("/Path/") ||
            virtualPath.StartsWith("~/Path/")) && virtualPath.EndsWith(".cshtml"))
        {
            String name = virtualPath.Replace("/Path/", "").Replace(".cshtml", "");
            Uri uri = new Uri("http://www.example.com/Handler.ashx?path=" + name);
            return new WebCacheDependency(uri.ToString());
        }

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

    public override bool FileExists(string virtualPath)
    {
        if ((virtualPath.StartsWith("/Path/") || 
            virtualPath.StartsWith("~/Path/")) && virtualPath.EndsWith(".cshtml"))
            return true;

        return base.FileExists(virtualPath);
    }

    public override VirtualFile GetFile(string virtualPath)
    {
        if (virtualPath.StartsWith("/Path/") || virtualPath.StartsWith("~/Path/"))
            return new TemplateVirtualFile(virtualPath);

        return base.GetFile(virtualPath);
    }
}

我还实现了一个自定义(虚拟)CacheDependency

public class WebCacheDependency : CacheDependency
{
    public WebCacheDependency(String url)
    {
        this.SetUtcLastModified(DateTime.UtcNow);
    }
}

现在有两件事不起作用。首先,所有加载的视图都被缓存,其次,文件内的代码(@Html.ActionLink ...等)不起作用,它只是给出一个错误“缺少程序集”。

有人知道如何解决这两个问题吗?

已经有第二个问题的解决方案 (link) 但是我真的不明白如何在 FileExists 方法中解决这个问题。

谢谢!

更新:错误消息的图像

【问题讨论】:

    标签: asp.net-mvc-3 razor virtualpathprovider viewbag cache-dependency


    【解决方案1】:

    您是否为 Razor 正确设置了 web.config?如果您不指定WebViewPagepageBaseType,您将无法访问ViewBag,因为它不在默认基本类型WebPageBase 中。

    您的 web.config 应该如下所示:

    <system.web.webPages.razor>
      <pages pageBaseType="System.Web.Mvc.WebViewPage">
        [...]
      </pages>
    </system.web.webPages.razor>
    

    注意 pageBaseType 属性。更多信息在这里:http://msdn.microsoft.com/en-us/library/system.web.webpages.razor.configuration.razorpagessection.pagebasetype(v=vs.99).aspx

    默认情况下,PageBaseType 的默认值为System.Web.WebPages.WebPage

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 1970-01-01
      相关资源
      最近更新 更多