In your scenario, you want to create the connection string at run time, based on the user input. So storing the connection string in the web.config file is not a good solution, espectially for a web application where you are going to have multiple users accessing your application at the same time (they will overwrite each other!).
What you need to do is to create a new connection string object based on the user input. You can use the
SqlConnectionStringBuilder
class for that purpose.
See
https://msdn.microsoft.com/en-us/library/ms254947(v=vs.110).aspx[
^]
If you are using Entity Framework, you can pass a connection string to the
DbContext
constructor:
public DbContext(string nameOrConnectionString)
Member of System.Data.Entity.DbContext
Summary:
Constructs a new context instance using the given string as the name or connection string for the database to which a connection will be made. See the class remarks for how this is used to create a connection.
Parameters:
nameOrConnectionString: Either the database name or a connection string.
IMPORTANT: risk of connection string injection attack!
A connection string injection attack can occur when dynamic string concatenation is used to build connection strings that are based on user input. If the string is not validated and malicious text or characters not escaped, an attacker can potentially access sensitive data or other resources on the server.
You've been warned!