Skip to content

Instantly share code, notes, and snippets.

@vmilev
Last active April 28, 2017 14:01
Show Gist options
  • Save vmilev/4d40d2bbd8c371b8147f709883c395da to your computer and use it in GitHub Desktop.
Save vmilev/4d40d2bbd8c371b8147f709883c395da to your computer and use it in GitHub Desktop.
URL Rewriter
<rewriteMaps>
<rewriteMap name="StaticRedirects">
<add key="old_url" value="new_url" />
</rewriteMap>
</rewriteMaps>
//1) We declare a dictionary to store the content of the rewritemap.config
private static IDictionary<string, string> rewriteMaps;
//2) Next, we add the following code inside Application_Start in your Global.asax.cs
//This will parse the config file and load it to a dictionary which ensures the uniqueness of each source URL.
//Feel free to extract this to a separate method to keeps thing clean.
protected void Application_Start(object sender, EventArgs e)
{
rewriteMaps = XDocument.Load(Server.MapPath("~/rewriteMaps.config"))
.Element("rewriteMaps")
.Element("rewriteMap")
.Elements("add")
.ToDictionary(
el => el.Attribute("key").Value,
el => el.Attribute("value").Value);
}
//3) Finally perform the redirects (in our case 301s) when needed in the appropriate spot in the ASP.NET lifecycle.
//Feel free to extract this to a seperate method as well.
protected void Application_BeginRequest(object sender, EventArgs e)
{
var httpApplication = sender as HttpApplication;
if (httpApplication != null)
{
string requestPath = httpApplication.Context.Request.Path;
if(rewriteMaps.ContainsKey(requestPath))
{
HttpContext.Current.Response.RedirectPermanent(rewriteMaps[requestPath]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment