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のメリットを享受できません。

実際のcombressdllファイルのソースコードを変更せずに私のcdnを挿入する方法を知っている人はいますか?

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

数か月前に同じ問題に遭遇し、この投稿に出くわしました。web.config またはデータベース設定から「ベース URL」値を読み取り、それをすべての Combres 画像 URL に適用する独自の Combres フィルター (FixUrlsInCSSFilter) を作成することで、この問題を回避することができました。

それが誰かを助けることを願っています...

combres.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 から値を取得します。また、これを使用して、combres で処理されない画像のパスを構築します...

    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 に答える