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

邮差的信 提交于 2019-12-05 01:24:58

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/2507150/how-to-intercept-and-pre-process-querystrings-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!