In this tutorial, you will learn why the Request.Url property located inside of the HttpContext Class may not work as you would expect inside an Episerver initialization module. This tip will hopefully help save someone a few hours of head-scratching. On a recent project, we had a requirement to update the Episerver site definition entry with the current local development hostname via code whenever the site was launched. This would allow any developer to run the site locally, no matter their configuration. I thought the best place to add this code would be within an initialization module, however, I bumped into a few issues. When I tried debugging the module, by placing a debug statement on HttpContext.Current.Request.Url the contents of the property looked like this:

Issues With The HTTPContext Url Doesn't Set Episerver Initialization Module 1

The site was meant to be running on localhost:54323, however, as you can see the hostname and port weren't correct. After some research, I discovered that an initializable module is run very early on in the .NET request pipeline. If you place a breakpoint in your initialization module, you will notice that it gets triggered very early on. The code below will be run before any of your custom code inside of the application_start is run within global.ascx:

Conceptually, this makes sense. When you want to configure Episerver on boot-up, you want to do this before the application is fully loaded. You do not want to do this after the site has been fully configured. The initialization module is run so early, that only the IPv4 IP has been set in the context. This screenshot was taken on the same breakpoint as above, except after the application had fully started. As you can see the HostNameType has switched from IPv4 to DNS and the port is now correct:

Issues With The HTTPContext Url Doesn't Set Episerver Initialization Module 2

This behaviour may seem unexpected, however, if you swat-up on the MVC pipeline, it makes sense. The HTTP context doesn't fully initialise until after the Episerver initialization modules run. The takeaway from this article is that you can't fully trust that everything in the HTTP context is fully set yet within an initialization module. When you are creating an initialization module, it's best to try and not use anything that's dependant on the current request. If you need to do things based on the current request, it will be a lot safer if you do those things AFTER the application has loaded.

In my situation, I had a few options like add each developer's hostname into config and use transforms. In general, I'd always recommend working with the framework rather than trying to push a square peg through a round hole. I hope this makes sense to you. Happy Coding 🤘