summaryrefslogtreecommitdiffstats
path: root/samples/ProviderPortal/Code/URLRewriter.cs
blob: 78bf53e4849c3eada25aed7ed399804d5b9f0a90 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System.Configuration;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;

// nicked from http://www.codeproject.com/aspnet/URLRewriter.asp
namespace ProviderPortal {
	public class URLRewriter : IConfigurationSectionHandler {
		public static log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		protected XmlNode _oRules = null;

		protected URLRewriter() { }

		public string GetSubstitution(string zPath) {
			Regex oReg;

			foreach (XmlNode oNode in _oRules.SelectNodes("rule")) {
				// get the url and rewrite nodes
				XmlNode oUrlNode = oNode.SelectSingleNode("url");
				XmlNode oRewriteNode = oNode.SelectSingleNode("rewrite");

				// check validity of the values
				if (oUrlNode == null || string.IsNullOrEmpty(oUrlNode.InnerText)
					|| oRewriteNode == null || string.IsNullOrEmpty(oRewriteNode.InnerText)) {
					Logger.Warn("Invalid urlrewrites rule discovered in web.config file.");
					continue;
				}

				oReg = new Regex(oUrlNode.InnerText, RegexOptions.IgnoreCase);

				// if match, return the substitution
				Match oMatch = oReg.Match(zPath);
				if (oMatch.Success) {
					return oReg.Replace(zPath, oRewriteNode.InnerText);
				}
			}

			return null; // no rewrite
		}

		public static void Process() {
			URLRewriter oRewriter = (URLRewriter)System.Configuration.ConfigurationManager.GetSection("urlrewrites");

			string zSubst = oRewriter.GetSubstitution(HttpContext.Current.Request.Path);

			if (!string.IsNullOrEmpty(zSubst)) {
				Logger.InfoFormat("Rewriting url '{0}' to '{1}' ", HttpContext.Current.Request.Path, zSubst);
				HttpContext.Current.RewritePath(zSubst);
			}
		}

		#region Implementation of IConfigurationSectionHandler
		public object Create(object parent, object configContext, XmlNode section) {
			_oRules = section;

			return this;
		}
		#endregion
	}
}