Website runs fine locally but crashes on Windows Azure

I've just published my application to my Windows Azure website. On my site I get the users IP address with the following code:

ip = HttpContext.Current.Request.UserHostAddress;

It works fine when I run it on localhost, however when I run it on Azure it crashes - I even tried catching the exception but it appears it doesn't throw any.

Furthermore when I remote debug the website I cannot see the "Current" property of the HttpContext - all it says is:

Cannot evaluate expression because the code of the current method is optimized.

Furthermore I can see that I can get the IP in the controller with ease - the problem is only when I call the HttpContext.Current.Request.UserHostAddress outside the controller.

Anyone who knows what the problem could be?

Answers


HttpContext is not available when using IIS integrated mode until after Application_Start has finished running.

To get around this, you can use a singleton pattern to read the setting and store it until the application recycles.

public class IPService
{
    private static string ip = string.Emtpy;

    public static string GetIP()
    {
        if (string.IsNullOrEmpty(this.ip))
        {
            this.ip = HttpContext.Current.Request.UserHostAddress;
        }

        return this.ip;
    }
}

Then whenever you need access to the IP, you can call:

var ip = IPService.GetIP();

Just be sure not to call it during application startup.


Need Your Help