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 researching, I found out that the 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 one in your global.ascx application_start, e.g. this snippet will always trigger after all initialization module code:
private void Application_BeginRequest(object source, EventArgs e)
var url = HttpContext.CUrrent.Request.Url;
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. In my situation, 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.. and looking how I'd expect.
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. 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.
Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge