Looking for a HTTPHandler to modify pages on the fly to point to a CDN

…衆ロ難τιáo~ 提交于 2019-11-30 13:57:43

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.

For example:

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);
    }
}

and register in web.config:

<httpModules>
  <add name="CdnModule" type="MyApp.CdnModule, MyApp"/>
</httpModules>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!