Asp. NET two global variable settings and reads

Source: Internet
Author: User
Tags config reference

This article describes how global variables are used in two asp.net projects. web.config files and gloab files. The following are described separately:

Method One: Web.config file

--Settings:

Adding key keys to the Web.config file is implemented by the tag, but appSettings tags are usually placed in ... tag outside. Cases:

  <configration>
  <appSettings>
  <add key="connString1" value="server=localhost;user id=sa;pwd=;database=数据库名字"/>
  <add key="connString2" value="provider=Microsoft.Jet.OleDb.4.0;Data Source=数据库路径"/>
  </appSettings>
  <system.web>
  </system.web>
  </configration>

--read:

To reference these database connection strings in code, You need to add a reference to the System.Configuration namespace that contains the ConfigurationSettings class in the namespace, and its static method ConfigurationSettings.AppSettings property to get the web.config text The section in the piece is set, and the value read is string type. For example:

  using System.Configuration;
  string conn1 = ConfigurationSettings.AppSettings["connString1"];
  string conn2 = ConfigurationSettings.AppSettings["connString2"];
  SQLConnection myConn1 = new SQLConnection(conn1);
  OleDbConnection myConn2 = new OleDbConnection(conn2);
  在VS2005中, ConfigurationSettings.AppSettings 可以换成 ConfigurationManager.AppSettings
  

Method Two: Gloab file

--Settings:

Adding in the global file

  protected void Session_Start(Object sender, EventArgs e)
  {
  Session["sqlConnectionString"] = "uid=Username;pwd=password;database=MyTest;server=Localhost;Connect Timeout=300";
  }
  

--read:

Application in code:

  String strConnection=Session["sqlConnectionString"].ToString();
  sqlConnection_1=new SqlConnection(strConnection);
  

Recommended to use the first way! More flexible, hahaha.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.