ASP.Net Combres and Combres MVC with Cloudfront
本文关键字:Combres with Cloudfront MVC and Net ASP | 更新日期: 2023-09-27 18:20:23
目前我正在使用AmazonCloudfront为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的这些文件中获得好处。
有没有人知道如何在不更改actall-compress dll文件源代码的情况下插入我的cdn?
我对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?
几个月前我遇到了同样的问题,刚刚看到了这篇文章。我可以通过制作自己的Combres过滤器(FixUrlsInCSSFilter)来绕过它,该过滤器将从web.config或数据库设置中读取"基本Url"值,并将其应用于所有Combres图像Url。
希望它能帮助别人。。。
combres.xml:
<combres xmlns='urn:combres'>
<filters>
<filter type="MySite.Filters.FixUrlsInCssFilter, MySite" />
</filters>
FixUrlsInSFilter-其中大部分是从原始反射文件复制的
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>