问题描述
我想要做的就是创建(或者已经存在),将过滤HTML一个HttpHandler的产生ASP.NET使用内容分发网络(CDN)。例如,我想引用改写像这样的:
What I'm trying to do is create (or perhaps one already exists) a HTTPHandler that will filter the HTML generated ASP.NET to use the content delivery network (CDN). For example, I want to rewrite references such as this:
/Portals/_default/default.css
到
http://cdn.example.com/Portals/_default/default.css
我完全乐意使用正则表达式匹配初始字符串。这样的正则表达式模式可能是:
I'm perfectly happy using RegEx to match the initial strings. Such a regex patterns might be:
href=['"](/Portals/.+\.css)
或
src=['"](/Portals/.+\.(css|gif|jpg|jpeg))
这是一个DotNetNuke的网站,我真的不拥有控制权产生的所有HTML所以这就是为什么我要与一个HttpHandler做到这一点。这样的变化可以做到页后生成。
This is a dotnetnuke site and I don't really have control over all the HTML generated so that's why I want to do it with an HTTPHandler. That way the changes can be done post-page generation.
推荐答案
您可以写一个响应滤波器可自定义HTTP模块中进行注册,而且还会修改所有网页生成的HTML运行您呈现正则表达式。
You could write a response filter which can be registered in a custom HTTP module and which will modify the generated HTML of all pages running the regex you showed.
例如:
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));
}
}
,然后写一个模块:
and then write a module:
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中注册:
and register in web.config:
<httpModules>
<add name="CdnModule" type="MyApp.CdnModule, MyApp"/>
</httpModules>
这篇关于寻找一个HttpHandler的修改对飞页指向一个CDN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!