【问题标题】:How to intercept and pre-process QueryStrings in Asp.Net如何在 Asp.Net 中拦截和预处理 QueryStrings
【发布时间】:2010-03-24 11:16:11
【问题描述】:

我们通过电子邮件向客户发送注册网址。一些电子邮件客户端正在将 url 变成

url <url>

我认为当用户将电子邮件转发给自己时可能会发生这种情况,此时电子邮件客户端会重新格式化原始电子邮件(可能)

例如

https://my.app.com/login.aspx?param=var

变成

https://my.app.com/login.aspx?param=var%20%3Chttps://my.app.com/login.aspx?param=var%3E

正确产生 System.Web.HttpRequestValidationException:检测到潜在危险的 Request.QueryString 值

我应该在代码中的什么位置拦截这些实例并清理 url,以便将用户重定向到 url 的原始形式?

global.asax? 页面初始化? Http处理程序? 管道?

【问题讨论】:

    标签: asp.net query-string sanitization


    【解决方案1】:

    您可以在 Global Application_BeginRequest 或 HttpModule 中的同一事件中捕获它。

    全球

    using System;
    using System.Web;
    
    namespace MassageIncomingRequestUrl
    {
        public class Global : HttpApplication
        {
            protected void Application_BeginRequest(object sender, EventArgs e)
            {
                var app = (HttpApplication) sender;
                string path = app.Context.Request.Url.PathAndQuery;
                int pos = path.IndexOf("%20%3C");
                if (pos > -1)
                {
                    path = path.Substring(0, pos);
                    app.Context.RewritePath(path);
                }
            }
        }
    }
    

    模块

    using System;
    using System.Web;
    
    namespace MassageIncomingRequestUrl
    {
        public class UrlMungeModule : IHttpModule
        {
            #region IHttpModule Members
    
            public void Init(HttpApplication context)
            {
                context.BeginRequest += BeginRequest;
            }
    
            public void Dispose()
            {
                //nop
            }
    
            #endregion
    
            private static void BeginRequest(object sender, EventArgs e)
            {
                var app = (HttpApplication)sender;
                string path = app.Context.Request.Url.PathAndQuery;
                int pos = path.IndexOf("%20%3C");
                if (pos>-1)
                {
                    path = path.Substring(0,pos);
                    app.Context.RewritePath(path);
                }
    
            }
        }
    }
    

    无论您在浏览器地址中看到什么,这都会使用请求中的正确查询字符串处理您的请求。您也许可以采取额外的步骤从报告的 url 中删除垃圾,但这主要是为了美观。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 2018-07-21
      • 1970-01-01
      相关资源
      最近更新 更多