Today's post is a quick one that may help save someone a few hours of head-scratching. On a recent project, we had a requirement to update the Episerver site definition with the current hostname via code. I thought it would be a brilliant idea to do this in an initialization module, however, I bumped into a few issues with the HTTP context, around the Request.Url and localhost.
When I tried debugging the module, using HttpContext.CUrrent.Request.Url via Visual Studio my Request. Url property looked like this:
The site was meant to be running on localhost:54323. As you can see the hostname and port weren't correct. After some research, I found out that an initializable module is run very early on in the request context. if you place a breakpoint in your initialization module, it will be hit before the 'global.ascx' application_start life-cycle method is triggered. This snippet will always run after an initialization module:
This makes sense as in general when you want to configure Episerver, you want to do this before the application is fully loaded and you can't do this after the site has been fully configured in the pipeline. I
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 request as above, except after the application had fully started, the HostNameType has switched from IPv4 to DNS and the port, etc..
This behavior may seem unexpected, but, if you read up on the MVC pipeline, it all makes sense as the context doesn't set itself up correctly until after the application start and as Episerver initialization modules get called way before that, it makes sense that you won't get a fully resolved HTTP context.
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 examples, I had a few options, run the code later, add the 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.