c# - 寻找一个 HTTPHandler 来动态修改页面以指向 CDN

标签 c# asp.net dotnetnuke cdn

我想做的是创建(或者可能已经存在)一个 HTTPHandler,它将过滤 HTML 生成的 ASP.NET 以使用内容分发网络 (CDN)。例如,我想重写这样的引用:

/Portals/_default/default.css

http://cdn.example.com/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/

相关文章:

asp.net - 修改Asp gridview boundfield

c# - 使用 HtmlAgilitypack 问题解析表

c# - 如何从网页启动 Windows 应用程序?

c# - 使用 C# 从服务名称中获取进程 ID

c# - 同时排序 (C#)?

c# - 如何使用 razor 在 html 中迭代列表变量

c# - 连接到 CRM

c# - Microsoft App-V 和硬件 ID

c# - 使用 LINQtoSQL 将记录计数值插入数据库表

c# - DotNetNuke 使用自定义 url 向模块菜单添加操作