加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 渲染位于远程服务器上的部分视图

发布时间:2020-12-16 06:38:42 所属栏目:asp.Net 来源:网络整理
导读:我有一个服务器,包含一些部分视图文件. 我如何从其他服务器加载文件到 Html.Partial? 喜欢: @Html.Partial("http://localhost/PartialServer/view/calculator.cshtml"); 我可以覆盖部分从网址加载吗? Asp.net MVC是框架. 解决方法 首先,在?/ Views /文件
我有一个服务器,包含一些部分视图文件.
我如何从其他服务器加载文件到 Html.Partial?
喜欢:

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

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

Asp.net MVC是框架.

解决方法

首先,在?/ 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时才会起作用),但不建议这样做.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读