【问题标题】:How to maintain CDN image links in dev and production sites?如何维护开发和生产站点中的 CDN 图像链接?
【发布时间】:2010-08-29 22:32:18
【问题描述】:

我有这个 ASP.NET MVC 应用程序,现在我想将图像链接分离到 CDN。 目前,图像通常具有以下标记代码:

<%= Html.ActionLinkWithImage("/Content/Img/Image1.png" ...

这在使用本地 Web 服务器 (Cassini) 的开发中运行良好,在发布产品服务器时也适用。
但现在我希望生产 URL 类似于:

http://cdn.com/Img/Image1.png

如何让它以一种简单的方式工作,以便它在 dev 中和发布到 prod 后无缝地工作?

【问题讨论】:

    标签: asp.net-mvc hyperlink cdn


    【解决方案1】:

    您可以创建一个 URL 扩展方法,该方法将根据 Web.config 文件(或其他文件)中的值生成调试 URL 或实时 URL。

    public static MvcHtmlString CDNImageLink(this UrlHelper url, string imageName)
    {
        string urlFormat;
        if((bool)ConfigurationManager.AppSettings["Debug"])
            urlFormat = "/Content/Img/{0}";
        else
            urlFormat = "http://cdn.com/Img/{0}";
    
        return MvcHtmlString.Create(string.Format(urlFormat, imageName));
    }
    

    然后,您可以在任何需要图像 url 的地方使用此扩展方法(包括 Html 扩展方法):

    public static MvcHtmlString ActionLinkWithImage(this HtmlHelper html, string imageName)
    {
         UrlHelper Url = new UrlHelper(html.ViewContext.RequestContext);
         string imageUrl = Url.CDNImageLink(imageName);
         // generate the rest of the ActionLink using the imageUrl
    }
    

    确保你有using 声明的名称空间,其中 Url 扩展方法位于声明 HTML 扩展方法的文件的顶部,否则它不会识别它。

    【讨论】:

    【解决方案2】:

    您还可以修改您的主机文件以将您的 cdn 域重定向到另一个 IP 地址。我一直使用它来将 static.myresources.com 重定向到 localhost,它使您的 html 非常干净。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-14
      • 1970-01-01
      • 2011-09-29
      • 1970-01-01
      • 2010-09-17
      • 2022-08-05
      • 1970-01-01
      相关资源
      最近更新 更多