Custom URLRewriting with XML and Global.asax

utilizes my custom DocParser class here

 void Application_BeginRequest(object sender, EventArgs e)
        //string path = Request.Url.ToString();
        string path = Request.Path;

        if (Regex.IsMatch(path.ToLower(), ".*[.](jpg|png|gif|css|js|pdf|ico|woff|svg|eot|ttf)$"))
            //var h = Regex.Replace(path.ToLower(), ".*/(.*)/(.*)$", "~/$1/$2", RegexOptions.Singleline);
        //TODO: authorize user/request
 DocParser dp = new DocParser(Server.MapPath("~/rewrite.xml"));
        var rules = dp.GetElements("*/rule");
        foreach (var r in rules)
            if (string.IsNullOrEmpty(r.match_url)) {
                Shared.HandleError("Global.asax::null or empty match_url encountered");

            if (string.IsNullOrEmpty(r.action_url))
                Shared.HandleError("Global.asax::null or empty action_url encountered");
            if (Regex.IsMatch(path, r.match_url,RegexOptions.IgnoreCase))
                List<object> qsvars = new List<object>();

                foreach (Match m in Regex.Matches(path, r.match_url, RegexOptions.IgnoreCase))
                    for (int i=1;i<m.Groups.Count;i++)
                //Context.RewritePath(string.Format(r.action_url,qsvars.ToArray()) + "&rewrite=1");
                Context.RewritePath(string.Format(r.action_url, qsvars.ToArray()));

rewrite.xml examples

<?xml version="1.0" encoding="utf-8" ?>
  <rule match_url="^/home" action_url="~/home.aspx" />
  <rule match_url="^/login" action_url="~/default.aspx" />
  <rule match_url="^/register" action_url="~/welcome/register.aspx" />
  <rule match_url="^/logout" action_url="~/logout.aspx" />
  <rule match_url="^/default/(.*)" action_url="~/default.aspx?q={0}" />
  <rule match_url="^/test/(.*)/(.*)" action_url="~/test.aspx?q={0}&amp;r={1}" />

About Ronnie Diaz

Ronnie Diaz is an enterprise software engineer responsible for front-end and back-end development for companies in many industries. Heavily involved in cloud development, online retail, e-commerce and electronic ordering, fulfillment and customer relational systems.

Posted on December 13, 2013, in .NET Reference, Programming & Development and tagged , , , , , , , , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: