Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 rightly 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?

like image 439
Nick Allen Avatar asked Nov 05 '22 15:11

Nick Allen


1 Answers

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.

like image 64
Sky Sanders Avatar answered Nov 15 '22 05:11

Sky Sanders