渲染位于远程服务器上的部分视图

meh*_*ehr 4 asp.net-mvc asp.net-mvc-partialview razor

我有一个服务器,包含一些部分视图文件.我如何从其他服务器加载文件到Html.Partial?喜欢:

@Html.Partial("http://localhost/PartialServer/view/calculator.cshtml");
Run Code Online (Sandbox Code Playgroud)

我可以覆盖部分从网址加载吗?

Asp.net MVC是框架.

hai*_*770 7

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

HtmlHelper使用RemotePartial方法扩展:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用如下:

@Html.RemotePartial("http://localhost/PartialServer/view/calculator.cshtml")
Run Code Online (Sandbox Code Playgroud)

您也可以Partial使用上面的实现替换原始方法(只有在传递的路径是远程URL时才会起作用),但不建议这样做.

  • +1非常聪明的解决方案.我还想添加一种重置缓存的方法. (2认同)
  • @MiBu,谢谢.我同意应该有一种控制缓存的方法.可能还需要处理异常,我只想提供核心功能. (2认同)