开发者

How to intercept and pre-process QueryStrings in Asp.Net

We send out registration urls to clients via email. Some of the email clients are turning the url into

url <url>

I think it may be happening when users forward the email onto themselves at which point the email client re-formats the original email (maybe)

E.g.

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

Becomes

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

Which right开发者_如何学Pythonly produces System.Web.HttpRequestValidationException: A potentially dangerous Request.QueryString value was detected

Where in the code should I intercept these instances and santize the url so that the user is re-directed onto the original form of the url?

global.asax? Page_Init? HttpHandler? Pipeline?


You can catch it in Global Application_BeginRequest or in the same event in an HttpModule.

Global

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

Module

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

        }
    }
}

This will get your request processed with the correct query string in the Request, regardless of what you see in the browser address. You may be able to take extra steps to remove the garbage from the reported url but that is mainly just aesthetics.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜