Friday, January 15, 2010

Dynamically update Url Mappings in Web.Config

One of the most useful yet underused additions to ASP.Net 2.0 was Url Mapping. This feature alone has caused a lot of noise in the blogsphere. Complaints range from the fact that you need an entry for every mapping to the fact that the mappings are not dynamic because they reside in the static web.config file.

Well ... that is all true. It is also true that if you update web.config in code, the application object is restarted and users lose Session state.

But, if Url Mappings is say, used for a standard blog webpage:
  A - How many entries are in a Blog? Even if we are talking a thousand or so entries eventually, will that few lines cause the ASP.Net engine problems? I wouldn't think so.
  B - How often would the webmaster be updating the Url Mappings? Once per posting. Even if the visitors loose Session - its not like it is happening every hour or so.
  C - What is a simple site doing with Session in the first place?

Well, I'm adding Url Mapping to my personal website and I've got a page that when called will automatically update the Url Mappings in web.config from the database, but only when a new mapping is needed.

And yes, I have session and viewstate shut off!

Code Snippet



  1. protected void Page_Load(object sender, EventArgs e)

  2. {

  3. var config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

  4. var section = (UrlMappingsSection)config.GetSection("system.web/urlMappings");


  5. var catArray = new ArrayList();

  6. var arcArray = new ArrayList();


  7. bool AnyChanges = false;


  8. foreach (var bd in BaseData.BlogDataList)

  9. {

  10. foreach (var strCategory in bd.Categories)

  11. {

  12. if (!catArray.Contains(strCategory) && !section.UrlMappings.AllKeys.Contains("~/" + strCategory))

  13. {

  14. catArray.Add(strCategory);

  15. section.UrlMappings.Add(new UrlMapping("~/" + strCategory, "~/Default.aspx?Category=" + strCategory));

  16. AnyChanges = true;

  17. }

  18. }


  19. var strEntryDate = bd.EntryDate.ToString("MMMM yyyy");

  20. if (!arcArray.Contains(strEntryDate) && !section.UrlMappings.AllKeys.Contains("~/" + strEntryDate))

  21. {

  22. arcArray.Add(strEntryDate);

  23. section.UrlMappings.Add(new UrlMapping("~/" + strEntryDate, "~/Default.aspx?Archives=" + strEntryDate));

  24. AnyChanges = true;

  25. }


  26. }


  27. if (AnyChanges) config.Save();


  28. Response.Redirect("~/Default.aspx");

  29. }

  30. }


No comments: