Recently at MSDN Forums there were people asking how they can detect if their web application is running on the cloud or locally (Dev Storage). Well besides the obvious part, if you have code inside a Web Role or a Worker Role Start() method, this only exists on a cloud template but what if you want to make that check somewhere else, for example inside a Page_Load method or inside a library (dll)?

If you’re trying to detect it on the “UI” level, let’s say Page_Load, you can simply check your headers. Request.Headers["Host"] will do the trick. If it’s “localhost” or whatever you like it to be to can be used to determine if it’s running local.

But how about a Library? Are there any alternatives?

Well, it’s not the most bullet proof method, but it served me well until now and I don’t think it’s going to stop working as it’s a fundamental architecture element of Windows Azure. There are specific Environment properties that are raising a SecurityException as you’re not allowed to read them. One of them is MachineName. So, if Environment.MachineName is raising an exception then you’re probably running on the cloud. As I said it’s not bullet proof because if an IT administrator applies a CAS that restricts specific properties, it can still raise an exception but you get my point. A combination of tricks can give you the desired result.

PK.