ModuleRewriter.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.Text.RegularExpressions;
  3. using System.Configuration;
  4. using URLRewriter.Config;
  5. namespace URLRewriter
  6. {
  7. /// <summary>
  8. /// Provides a rewriting HttpModule.
  9. /// </summary>
  10. public class ModuleRewriter : BaseModuleRewriter
  11. {
  12. /// <summary>
  13. /// This method is called during the module's BeginRequest event.
  14. /// </summary>
  15. /// <param name="requestedRawUrl">The RawUrl being requested (includes path and querystring).</param>
  16. /// <param name="app">The HttpApplication instance.</param>
  17. protected override void Rewrite(string requestedPath, System.Web.HttpApplication app)
  18. {
  19. // log information to the Trace object.
  20. app.Context.Trace.Write("ModuleRewriter", "Entering ModuleRewriter");
  21. // get the configuration rules
  22. RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;
  23. // iterate through each rule...
  24. for(int i = 0; i < rules.Count; i++)
  25. {
  26. // get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)
  27. string lookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].LookFor) + "$";
  28. // Create a regex (note that IgnoreCase is set...)
  29. Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);
  30. // See if a match is found
  31. if (re.IsMatch(requestedPath))
  32. {
  33. // match found - do any replacement needed
  34. string sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(requestedPath, rules[i].SendTo));
  35. // log rewriting information to the Trace object
  36. app.Context.Trace.Write("ModuleRewriter", "Rewriting URL to " + sendToUrl);
  37. // Rewrite the URL
  38. RewriterUtils.RewriteUrl(app.Context, sendToUrl);
  39. break; // exit the for loop
  40. }
  41. }
  42. // Log information to the Trace object
  43. app.Context.Trace.Write("ModuleRewriter", "Exiting ModuleRewriter");
  44. }
  45. }
  46. }