Question

Recently I asked this :

Get Base URL of My Web Application

This worked to an extent in debug, as I use the VS Development server.

I then produced an Install, the install will then point to IIS 7.

I had :

    void Application_Start(object sender, EventArgs e)
    {
        _baseUrl = HttpContext.Current.Request.Url.ToString();
        ....
    }

But this threw the following error :

Request is not available in this context

I then did some reading up and here is why this happens :

http://mvolo.com/iis7-integrated-mode-request-is-not-available-in-this-context-exception-in-applicationstart

I then moved the code out from Application_Start to Application_BeginRequest, using the technique above as I found Application_BeginRequest was being executed several times.

But the problem is I need the Base URL of IIS 7, for use in Application_Start, and so I have a global string I tried to set in :

FirstRequestInitialization.Initialize(context);

But not surpriseingly when attempting this :

Application["BaseUrl"] = HttpContext.Current.Request.Url.ToString();

I get this error : 'Microsoft.Web.Administration.Application' is a 'type' but is used like a 'variable'

All I want is the Base URL of IIS 7.

I can't use Directory Entries as I can't support IIS 6.

How can I do this? Any workarounds? Can I execute AppCmd from VS?

Any help much appreciated. Thanks!

Was it helpful?

Solution

Short answer: you can't get it, because the websites do not have a single canonical base URI - a website (or rather, a web application) can be configured to answer to requests on any binding, any domain name, and any resource path - and a website can be reconfigured in the host webserver (IIS) without the application being made aware of this at all.

If you really want to store your "base URL" (even though such a thing doesn't really exist) then you can do it from within Application_BeginRequest like so:

private static readonly Object _arbitraryUrlLock = new Object();
private static volatile String _arbitraryUrl;

public void Application_BeginRequest() {
    if( _arbitraryUrl == null ) 
        lock( _arbitraryUrlLock )
            if( _arbitraryUrl == null ) 
                _arbitraryUrl = HttpContext.Current.Request.Url.ToString();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top