4

目前我正在使用 Amazon Cloudfront 为我的 ASP.Net MVC3 C# 站点上的静态对象提供服务。因此,所有静态资源都在资源之前附加了http://cdn.domainname.com/ 。

同时我使用combres和combred mvc来压缩和组合我的CSS和Javascript。

输出最小化组合文件的标签如下。

@Html.Raw(WebExtensions.CombresLink("siteCss"))
@Html.Raw(WebExtensions.CombresLink("siteJs"))

这会在我的网站上生成指向

<link rel="stylesheet" type="text/css" href="/combres.axd/siteCss/-63135510/"/>
<script type="text/javascript" src="/combres.axd/siteJs/-561397631/"></script> 

正如您所看到的,我的 cloudfront cdn 不在它前面,所以我没有通过这些文件获得 cloudfront 的好处。

有没有人知道如何插入我的cdn而不更改实际的combrress dll文件的源代码?

4

2 回答 2

4

我不熟悉 Cloudfront,但使用 Combres(最新版本),您可以更改主机名(在 /combres.axd... 之前附加为前缀...

 <resourceSets url="~/combres.axd"
                host="static.mysite.com"
                defaultDuration="365"
                defaultVersion="auto"
                defaultDebugEnabled="false"
                defaultIgnorePipelineWhenDebug="true"
                localChangeMonitorInterval="30"
                remoteChangeMonitorInterval="60"
                > 

请让我知道这种方法是否适用于 CloudFront?

于 2012-02-08T16:04:44.143 回答
1

几个月前我遇到了同样的问题,刚刚看到这篇文章。我可以通过制作自己的 Combres 过滤器 (FixUrlsInCSSFilter) 来解决它,该过滤器将从 web.config 或数据库设置中读取“Base Url”值并将其应用于所有 Combres 图像 url。

希望它可以帮助那里的人...

梳子.xml

<combres xmlns='urn:combres'>
  <filters>
    <filter type="MySite.Filters.FixUrlsInCssFilter, MySite" />
  </filters>

FixUrlsInCssFilter - 其中大部分是从原始反射文件中复制的

    public sealed class FixUrlsInCssFilter : ISingleContentFilter
{
    /// <inheritdoc cref="IContentFilter.CanApplyTo" />
    public bool CanApplyTo(ResourceType resourceType)
    {
        return resourceType == ResourceType.CSS;
    }

    /// <inheritdoc cref="ISingleContentFilter.TransformContent" />
    public string TransformContent(ResourceSet resourceSet, Resource resource, string content)
    {
        string baseUrl = AppSettings.GetImageBaseUrl();

        return Regex.Replace(content, @"url\((?<url>.*?)\)", match => FixUrl(resource, match, baseUrl),
            RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.ExplicitCapture);
    }

    private static string FixUrl(Resource resource, Match match, string baseUrl)
    {
        try
        {
            const string template = "url(\"{0}\")";
            var url = match.Groups["url"].Value.Trim('\"', '\'');

            while (url.StartsWith("../", StringComparison.Ordinal))
            {
                url = url.Substring(3); // skip one '../'
            }

            if (!baseUrl.EndsWith("/"))
                baseUrl += "/";

            if (baseUrl.StartsWith("http"))
            {
                return string.Format(CultureInfo.InvariantCulture, template, baseUrl + url);
            }
            else
                return string.Format(CultureInfo.InvariantCulture, template, (baseUrl + url).ResolveUrl());
        }
        catch (Exception ex)
        {
            // Be lenient here, only log.  After all, this is just an image in the CSS file
            // and it should't be the reason to stop loading that CSS file.
            EventManager.RaiseExceptionEvent("Cannot fix url " + match.Value, ex);
            return match.Value;
        }
    }
}

#region Required to override FixUrlsInCssFilter for Combres

public static class CombresExtensionMethods
{
    /// <summary>
    ///   Returns the relative HTTP path from a partial path starting out with a ~ character or the original URL if it's an absolute or relative URL that doesn't start with ~.
    /// </summary>
    public static string ResolveUrl(this string originalUrl)
    {
        if (string.IsNullOrEmpty(originalUrl) || IsAbsoluteUrl(originalUrl) || !originalUrl.StartsWith("~", StringComparison.Ordinal))
            return originalUrl;

        /* 
         * Fix up path for ~ root app dir directory
         * VirtualPathUtility blows up if there is a 
         * query string, so we have to account for this.
         */
        var queryStringStartIndex = originalUrl.IndexOf('?');
        string result;
        if (queryStringStartIndex != -1)
        {
            var baseUrl = originalUrl.Substring(0, queryStringStartIndex);
            var queryString = originalUrl.Substring(queryStringStartIndex);
            result = string.Concat(VirtualPathUtility.ToAbsolute(baseUrl), queryString);
        }
        else
        {
            result = VirtualPathUtility.ToAbsolute(originalUrl);
        }

        return result.StartsWith("/", StringComparison.Ordinal) ? result : "/" + result;
    }

    private static bool IsAbsoluteUrl(string url)
    {
        int indexOfSlashes = url.IndexOf("://", StringComparison.Ordinal);
        int indexOfQuestionMarks = url.IndexOf("?", StringComparison.Ordinal);

        /*
         * This has :// but still NOT an absolute path:
         * ~/path/to/page.aspx?returnurl=http://www.my.page
         */
        return indexOfSlashes > -1 && (indexOfQuestionMarks < 0 || indexOfQuestionMarks > indexOfSlashes);
    }
}

#endregion

AppSettings 类 - 从 web.config 中检索值。我还使用它来构建未由梳子处理的图像的路径......

    public class AppSettings
{
    /// <summary>
    /// Retrieves the value for "ImageBaseUrl" if the key exists
    /// </summary>
    /// <returns></returns>
    public static string GetImageBaseUrl()
    {
        string baseUrl = "";

        if (ConfigurationManager.AppSettings["ImageBaseUrl"] != null)
            baseUrl = ConfigurationManager.AppSettings["ImageBaseUrl"];

        return baseUrl;
    }
}

web.config 值

<appSettings>
   <add key="ImageBaseUrl" value="~/Content/Images/" /> <!--For Development-->
   <add key="ImageBaseUrl" value="https://d209523005EXAMPLE.cloudfront.net/Content/Images/" /> <!--For Production-->
</appSettings>
于 2012-04-18T19:09:15.997 回答