从Web.config文件获取连接字符串中的asp.net [英] Get Connection String from Web.config in asp.net
问题描述
我想知道获得从asp.net web.config文件中的连接字符串的方式。
我刚刚才知道下面的路。
使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;
使用System.Configuration;
命名空间Sherserve.DataAccessLayer
{
公共类DBGateway
{
公共静态字符串conString;
公共DBGateway()
{
conString = ConfigurationManager.ConnectionStrings [测试]的ToString();
}
}
}
使用 ConfigurationManager.ConnectionStrings
即将唯一正确的方法,使用它与理智正确地检查你可以有这样的代码:
公共DBGateway()
{
ConnectionStringSettings mySetting = ConfigurationManager.ConnectionStrings [测试];
如果(mySetting == NULL || string.IsNullOrEmpty(mySetting.ConnectionString))
抛出新的异常(致命错误:缺少web.config文件中的连接字符串);
conString = mySetting.ConnectionString;
}
这将抛出的情况下,连接字符串缺少有用的错误,而不是神秘空对象的错误。
值得一提的是, ConnectionStringSettings
类覆盖的ToString()
方法:
公共重写字符串的ToString()
{
返回this.ConnectionString;
}
因此,这意味着,使用 ConfigurationManager.ConnectionStrings [测试]的ToString()
像 ConfigurationManager.ConnectionStrings相同[测试。ConnectionString的
但是你还是更好地履行完整性检查,并亲自它看起来更清洁的使用实际的财产,而不是依赖于类的给它。
I want to know the ways to get connection string from web.config file in asp.net.
I just only know the below way .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
namespace Sherserve.DataAccessLayer
{
public class DBGateway
{
public static string conString;
public DBGateway()
{
conString = ConfigurationManager.ConnectionStrings["test"].ToString();
}
}
}
Using the ConfigurationManager.ConnectionStrings
is about the only proper way, to use it properly with sanity check you can have such code:
public DBGateway()
{
ConnectionStringSettings mySetting = ConfigurationManager.ConnectionStrings["test"];
if (mySetting == null || string.IsNullOrEmpty(mySetting.ConnectionString))
throw new Exception("Fatal error: missing connecting string in web.config file");
conString = mySetting.ConnectionString;
}
This will throw useful error in case the connection string is missing, instead of cryptic "null object" error.
Worth to mention that the ConnectionStringSettings
class is overriding the ToString()
method:
public override string ToString()
{
return this.ConnectionString;
}
So it means that using ConfigurationManager.ConnectionStrings["test"].ToString()
is the same like ConfigurationManager.ConnectionStrings["test"].ConnectionString
however you still better perform sanity check and personally it looks cleaner to use the actual property and not depend on the class to give it.
这篇关于从Web.config文件获取连接字符串中的asp.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!