Last active
April 28, 2017 14:01
-
-
Save vmilev/4d40d2bbd8c371b8147f709883c395da to your computer and use it in GitHub Desktop.
URL Rewriter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<rewriteMaps> | |
<rewriteMap name="StaticRedirects"> | |
<add key="old_url" value="new_url" /> | |
</rewriteMap> | |
</rewriteMaps> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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