Skip to content

Instantly share code, notes, and snippets.

@rsyring
Created April 13, 2012 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsyring/2373367 to your computer and use it in GitHub Desktop.
Save rsyring/2373367 to your computer and use it in GitHub Desktop.
ASP.NET escaping WebResource.axd URLs
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace Some.Namespace.Utils {
public class PageBase : System.Web.UI.Page {
protected override void Render(HtmlTextWriter writer) {
StringBuilder renderedOutput = new StringBuilder();
StringWriter strWriter = new StringWriter(renderedOutput);
HtmlTextWriter tWriter = new HtmlTextWriter(strWriter);
// have .NET render the page using tWriter which will result in
// renderedOutput having the HTML of the page
base.Render(tWriter);
// escape the WebResource.axd URLS which do not escape their "&" in the
// query string. We want valid XHTML markup.
writer.Write(Helpers.EscapeWebResourceUrls(renderedOutput.ToString()));
}
}
public static class Helpers {
public static string EscapeWebResourceUrls(string input) {
string output = input.ToString();
//MatchCollection m = Regex.Matches(output, @"src=""/WebResource.axd([\?\&].+=([^&]+))+""");
MatchCollection m = Regex.Matches(output, @"src=""/WebResource.axd([\?\&].+=([^&""]+))+""");
if( m.Count > 0) {
for(int i = 0; i < m.Count; i++) {
string queryStringPart = m[i].Groups[1].Value;
string escapedQueryStringPart = Regex.Replace(queryStringPart, "&(?!(amp;))", "&amp;");
output = output.Replace(queryStringPart, escapedQueryStringPart);
}
}
return output;
}
}
}
// the tests
using System;
using NUnit.Framework;
using Some.Namespace.Utils;
namespace Some.Namespace.Tests.TestUtils {
[TestFixture]
public class HelpersTest {
[Test]
public void QuoteWebResource() {
string input = "something";
Assert.AreEqual(input, Helpers.EscapeWebResourceUrls(input));
input = @"<script src=""/WebResource.axd?d=PyP9M%2fFExI&t=634660651570000000"" type=""text/javascript""></script>";
string expect = @"<script src=""/WebResource.axd?d=PyP9M%2fFExI&amp;t=634660651570000000"" type=""text/javascript""></script>";
Assert.AreEqual(expect, Helpers.EscapeWebResourceUrls(input));
}
}
}
@ppaa660
Copy link

ppaa660 commented Apr 13, 2019

@ppaa660
Copy link

ppaa660 commented Apr 13, 2019

@ppaa660
Copy link

ppaa660 commented Apr 13, 2019

<script src="../Scripts/VisaRequestOracle.js" type="text/javascript"></script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment