Override HttpContext.Current.Request.Url property in c# to return the encoded URL

Viewed 476

In one of my applications I am using HttpContext.Current.Request.Url in aspx code to get the current page url. As the page url is being used in java script there is a high chance of passing malicious script in the url to make the JS function to break.

One option is that we can encode the url using

HttpUtility.HtmlEncode(HttpContext.Current.Request.Url)

but this piece of code is a part of user control (.ascx file), I have to change that in all those user control.

So is there any way I can override the

HttpContext.Current.Request.Url

property so that it will return the encoded url? So I can use some handler to tackle all the url property in application?

Thanks for your help.

1 Answers

You can't override HttpUtility.HtmlEncode because the method is a static method.

But I think you can try to use an extension method to do yours expect.

public static class UriExtension {
    public static string HtmlEncode(this Uri uri){
        HttpUtility.HtmlEncode(uri);
         // do the logic...

    }
}

You can call the method

HttpContext.Current.Request.Url.HtmlEncode()
Related