Reputation: 453
I want to create a global value inside asp net for getting SQL Server connection string.
Should I create a public read only string?
public static readonly string connectionString="myconnection string";
inside a class?
Or do I need to add a key value inside Web.Config
?
<connectionStrings>
<add name="SqlDatabase"
connectionString="yourConnectionString"
providerName="System.Data.SqlClient" />
</connectionStrings>
And to use it inside get or post request
public string Get(int id)
{
var connectionString = WebConfigurationManager.ConnectionStrings["SqlDatabase "].ConnectionString;
return "connectionString";
}
This string will be used from many client request at same time.
Upvotes: 0
Views: 1740
Reputation: 21
In cs file you can use it as:- SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.AppSettings["connection.connection_string"].ToString());
Upvotes: 0
Reputation: 10627
It goes in your web.config or appsettings.json (for .net core). Read about Dependency Injection to learn more about the new/cool/easy way to handle all this stuff.
Upvotes: 1
Reputation: 764
add your connection string in web config as
<connectionStrings>
<add name="DbContext"
connectionString="Server=localhost; Database=mydbname;
Integrated Security=True"; providerName="System.Data.SqlClient" />
</connectionStrings>
now read from the application using this code
System.Configuration.ConfigurationManager.
ConnectionStrings["DbContext"].ConnectionString;
thats how you can use it across applications and can change the connection string from web config after deployment of the application
Upvotes: 1