【问题标题】:Understanding HttpModules and URL manipulation了解 HttpModules 和 URL 操作
【发布时间】:2014-07-29 12:19:25
【问题描述】:

我正在处理的一个项目与一个 php 应用程序 (Revive AdServer FWIW) 集成。我们控制它部署到的服务器,但我认为更改代码是不可能的。 Revive 具有调用 javascript 代码,您可以将其部署到您希望投放广告的网站,当代码在这些网站上呈现时,它会调用 php 应用程序并根据传入的查询字符串智能地显示广告。

我们需要做的是在调用从其中一个站点发出之后、在它到达 php 应用程序并操纵查询字符串之前拦截调用。为此,我编写了一个 HttpModule,我们已将其添加到 php 应用程序的 IIS 中。代码如下:

public class AdServerModule : IHttpModule
{
    public void OnBeginRequest(object sender, EventArgs e)
    {
        var context = ((HttpApplication)sender).Context;
        var queryString = context.Request.QueryString;
        var readonlyProperty = queryString.GetType().GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
        readonlyProperty.SetValue(queryString, false, null);
        queryString.Add("foo", "bar");
        readonlyProperty.SetValue(queryString, true, null);
    }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(OnBeginRequest);
    }
}

在此示例中,您可以看到我正在使用反射将&foo=bar 添加到请求的查询字符串中。我不确定我是否误解了应该发生的事情,但我希望在请求中的某个地方看到这一点,但我没有。

此外,我并没有尝试过多地偶然发现 php 代码,但我相信它正在检查请求的 URL 以获取查询字符串值,因此看来我需要更改 URL 而不仅仅是操纵上下文。 Request.Query 字符串属性(似乎不一样)。我想知道是否需要实现 UrlRewriter(我不熟悉这样做)。在我看到的一个示例中,context.RewritePath() 被调用,但如果在 HttpModule 中使用这似乎会导致无限循环/堆栈溢出。

提前感谢您的帮助。

【问题讨论】:

    标签: c# query-string httpmodule request.querystring


    【解决方案1】:

    我能够弄清楚。事实证明,您确实需要使用 RewritePath() 方法。我最初没有正确使用它。这是我现在的代码:

    public class AdServerModule : IHttpModule
    {
        public void OnBeginRequest(object sender, EventArgs e)
        {
            var context = ((HttpApplication)sender).Context;
            var queryString = context.Request.QueryString;
            var readonlyProperty = queryString.GetType().GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
            readonlyProperty.SetValue(queryString, false, null);
            queryString.Add("foo", "bar");
    
            var path = GetVirtualPath(context);
            context.RewritePath(path, String.Empty, queryString.ToString());
    
            readonlyProperty.SetValue(queryString, true, null);
        }
    
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(OnBeginRequest);
        }
    
        private static string GetVirtualPath(HttpContext context)
        {
            string path = context.Request.RawUrl;
            var queryStringLength = path.IndexOf("?");
            path = path.Substring(0, queryStringLength >= 0 ? queryStringLength : path.Length);
            path = path.Substring(path.LastIndexOf("/") + 1);
            return path;
        }
    }
    

    你可以看到我在哪里添加了context.RewritePath() 调用。像魅力一样工作!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-20
      • 2019-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-15
      • 2011-12-23
      • 2014-08-28
      相关资源
      最近更新 更多