Creating a string in a web.config and use it in a web.api

32,722

Solution 1

If I understand what you want to do, it sounds like you don't want to use a connection string at all. Instead, use the Application Settings sections of your web.config file. For example

<configuration>
  <system.web> ... </system.web>
  <appSettings>
    <add key="MyAppSetting" value="A test value." />
  </appSettings>
</configuration>

This can then be used in your code by getting the value of

System.Configuration.ConfigurationManager.AppSettings["MyAppSetting"]

(C#) or

System.Configuration.ConfigurationManager.AppSettings("MyAppSetting")

(VB)

See MSDN for more information, or just search online for "asp.net AppSettings".

Solution 2

If you don't have a database to connect to (which is what I understood from your question), then you don't even need to have the <connectionStrings> section in your Web.config. That section is only needed if you are going to connect to a database.

If you do use a database, then the connectionString varies depending on several factors such as type of authentication, database product (MS SQL Server, MySQL), type of driver (ODBC, .NET), etc.

The "Provider Name" will depend on the database product that you are using. For example for SQL Server is "System.Data.SqlClient"

You can look at this site for a comprehensive list of database products and connection strings appropriate for each product for different authentication types, drivers used, etc.

Share:
32,722
user1415780
Author by

user1415780

Updated on April 26, 2020

Comments

  • user1415780
    user1415780 about 4 years

    I am new in the web development world and I would like to create a variable in the web.config file so that I can use it in the .NET portion of the web.api

    I found the following tutorials on how to do that :

    Setting up connection string in ASP.NET to SQL SERVER

    And

    http://www.connectionstrings.com/Articles/Show/store-connection-string-in-web-config

    I have the following question , I don t have a database to connect the string to(I will only use it in the web config so that I can easily change the string without having to go through code . so assuming that I am using it in the following way :

    <add name="ConnStringDb1" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
    

    What should I have in the connectionString and the providerName ?