0

Possible Duplicate:
How to check in ASP.NET MVC View if site is running on localhost or 127.0.0.1

I am using two entry for connection string in web.config, and i am using HttpContext.Current.Request.UserHostAddress for detection between deployment and development environment:

public static SqlConnection GetSqlConnection()
{
    if (HttpContext.Current.Request.UserHostAddress != "127.0.0.1")
    ...
    else
    ...
}

but problem is here, some times HttpContext.Current is null and raise exception (i.e: when scheduled task is runed in asp.net from global.asax). is there any general solution for this?

Community
  • 1
  • 1
Meh Man
  • 463
  • 1
  • 6
  • 22
  • IsLocal is a method of Request and some times Request is null. the above is not perfect solution – Meh Man Dec 30 '12 at 21:39

1 Answers1

4

You're supposed to change the connection string in the configuration file between environments. That's why they're stored in a configuration file in the first place, so you wouldn't have to do this.

I prefer to put connection strings in a separate file and not deploy it at all. The same can be done with other configuration that's environment specific. Another way is to use an XML transform as a part of your build job to change the connection string when deploying into production.

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
  • ok but when we store connection string in web.config, we can use the method that defined in .net framework to read connection string. – Meh Man Dec 30 '12 at 21:41
  • 2
    Huh? Isn't that exactly what the configuration files are for? Reading stuff from? – Matti Virkkunen Dec 30 '12 at 21:43
  • No, but if exist any solution for web.config, it's better from your solution. your solution is good if there is not any other solution. – Meh Man Dec 30 '12 at 22:18
  • @mmtemporary: I still don't understand what you're trying to ask. Are you asking if you can put connection strings in a separate file and still use `ConfigurationManager` etc to read them? If so, the answer is yes. Google for the standard `configSource` attribute. – Matti Virkkunen Dec 30 '12 at 22:20
  • Thanks Matti, use of configSource is good – Meh Man Dec 30 '12 at 22:58