【问题标题】:Render partial views located on remote server渲染位于远程服务器上的部分视图
【发布时间】:2014-10-27 16:49:41
【问题描述】:

我有一个服务器来保存一些部分视图文件。 我如何将文件从另一台服务器加载到 Html.Partial ? 喜欢:

@Html.Partial("http://localhost/PartialServer/view/calculator.cshtml");

我可以覆盖部分以从 url 加载它吗?

Asp.net MVC 是框架。

【问题讨论】:

  • 远程 Url 是否真的会返回完整的 Razor 代码?
  • 不,我将配置存储库服务器以提供此文件类型。
  • 我假设答案是“是”。请求 URL 确实会返回完整的 Razor 代码...
  • 我认为这种方法是不可能的。我如何覆盖 Partial 来处理更多网址?

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


【解决方案1】:

首先,在您的~/Views/ 文件夹下创建一个名为_RemotePartialsCache 的新目录。

使用RemotePartial 方法扩展HtmlHelper

public static class HtmlExtensions
{
    private const string _remotePartialsPath = "~/Views/_RemotePartialsCache/";
    private static readonly IDictionary<string, string> _remotePartialsMappingCache = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);

    public static MvcHtmlString RemotePartial(this HtmlHelper helper, string partialUrl, object model = null)
    {
        string cachedPath;

        // return cached copy if exists
        if (_remotePartialsMappingCache.TryGetValue(partialUrl, out cachedPath))
            return helper.Partial(_remotePartialsPath + cachedPath, model);

        // download remote data
        var webClient = new WebClient();
        var partialUri = new Uri(partialUrl);
        var partialData = webClient.DownloadString(partialUrl);

        // save cached copy locally
        var partialLocalName = Path.ChangeExtension(partialUri.LocalPath.Replace('/', '_'), "cshtml");
        var partialMappedPath = helper.ViewContext.RequestContext.HttpContext.Server.MapPath(_remotePartialsPath + partialLocalName);
        File.WriteAllText(partialMappedPath, partialData);

        // save to cache
        _remotePartialsMappingCache[partialUrl] = partialLocalName;

        return helper.Partial(_remotePartialsPath + partialLocalName, model);
    }
}

然后按如下方式使用:

@Html.RemotePartial("http://localhost/PartialServer/view/calculator.cshtml")

你也可以用上面的实现替换原来的 Partial 方法(只有当传递的路径是远程 url 时才会起作用),但不建议这样做。

【讨论】:

  • +1 非常聪明的解决方案。我还会添加一种重置缓存的方法。
  • @MiBu,谢谢。我同意应该有一种方法来控制缓存。可能还需要异常处理,我只想提供核心功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多