我想做的是创建(或者可能已经存在)一个 HTTPHandler,它将过滤 HTML 生成的 ASP.NET 以使用内容分发网络 (CDN)。例如,我想重写这样的引用:
/Portals/_default/default.css
到
我非常高兴使用 RegEx 来匹配初始字符串。这样的正则表达式模式可能是:
href=['"](/Portals/.+\.css)
或
src=['"](/Portals/.+\.(css|gif|jpg|jpeg))
这是一个 dotnetnuke 站点,我实际上无法控制生成的所有 HTML,所以这就是我想使用 HTTPHandler 来完成它的原因。这样就可以在页面生成后完成更改。
最佳答案
你可以写一个 response filter它可以在自定义 HTTP 模块中注册,它将修改运行您显示的正则表达式的所有页面的生成的 HTML。
例如:
public class CdnFilter : MemoryStream
{
private readonly Stream _outputStream;
public CdnFilter(Stream outputStream)
{
_outputStream = outputStream;
}
public override void Write(byte[] buffer, int offset, int count)
{
var contentInBuffer = Encoding.UTF8.GetString(buffer);
contentInBuffer = Regex.Replace(
contentInBuffer,
@"href=(['""])(/Portals/.+\.css)",
m => string.Format("href={0}http://cdn.example.com{1}", m.Groups[1].Value, m.Groups[2].Value)
);
contentInBuffer = Regex.Replace(
contentInBuffer,
@"src=(['""])(/Portals/.+\.(css|gif|jpg|jpeg))",
m => string.Format("href={0}http://cdn.example.com{1}", m.Groups[1].Value, m.Groups[2].Value)
);
_outputStream.Write(Encoding.UTF8.GetBytes(contentInBuffer), offset, Encoding.UTF8.GetByteCount(contentInBuffer));
}
}
然后写一个模块:
public class CdnModule : IHttpModule
{
void IHttpModule.Dispose()
{
}
void IHttpModule.Init(HttpApplication context)
{
context.ReleaseRequestState += new EventHandler(context_ReleaseRequestState);
}
void context_ReleaseRequestState(object sender, EventArgs e)
{
HttpContext.Current.Response.Filter = new CdnFilter(HttpContext.Current.Response.Filter);
}
}
并在 web.config 中注册:
<httpModules>
<add name="CdnModule" type="MyApp.CdnModule, MyApp"/>
</httpModules>
关于c# - 寻找一个 HTTPHandler 来动态修改页面以指向 CDN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6061286/