无法从app.config获取连接字符串 [英] Can't get the connection string from app.config

查看:187
本文介绍了无法从app.config获取连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类库,其中包含由asp.net Web应用程序和WCF Web服务共享的类。库中的类需要从数据库中检索信息,因此库在app.config中具有用于连接字符串的条目,以及用于检索该连接字符串的方法。

I have a class library that contains classes shared by an asp.net web application and a WCF web service. The classes inside the library need to retrieve information from the database, and so the library has an entry in the app.config for the connection string, and a method that retrieves that connection string.

这是我在app.config中声明连接字符串的方式:

Here's how I declare my connection string in the app.config :

<configuration>
    <connectionStrings>
        <add name="connstring"
             connectionString="Data Source=MYSERVER;Initial Catalog=MY_DB;User Id=mylogin;Password=mypassword;"
             providerName="System.Data.SqlClient"/>
    </connectionStrings>
    [...]
</configuration>

这是检索连接字符串的方法:

And here's the method that retrieves the connection string :

Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Data.OleDb

Public Module modGen

    Public Function gGetConnectionString() As String

        Dim conn As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("connstring")
        Dim connString As String = conn.ConnectionString
        Return connString

    End Function

问题在于,方法运行时, conn的值将为 Nothing,然后引发以下异常:

The problem is that, when the method runs, "conn" gets "Nothing" for value and the following exception is then thrown :

System.TypeInitializationException was caught
  Message=The type initializer for 'CHK.TRK.CLS.modGen' threw an exception.
  Source=CHK.TRK.CLS
  TypeName=CHK.TRK.CLS.modGen
  StackTrace:
       at CHK.TRK.CLS.modGen.gGetConnectionString()
       at CHK.TRK.CLS.modAuth.CheckUser(String logon, String pwHash) in  H:\WorkSpace\CHKTRK\CHKTRK\CHKTRKClasses\Mod\modAuth.vb:line 141
       at CHK.TRK.CLS.modAuth.Authenticate(String logon, String pwhash) in H:\WorkSpace\CHKTRK\CHKTRK\CHKTRKClasses\Mod\modAuth.vb:line 9
       at CHKTRKWebService.CheckTrackService.Authenticate(String login, String pwHash) in H:\WorkSpace\CHKTRK\CHKTRK\CHKTRKWebService\CheckTrackService.svc.vb:line 20
  InnerException: System.NullReferenceException
       Message=Object reference not set to an instance of an object.
       Source=CHK.TRK.CLS
       StackTrace:
            at CHK.TRK.CLS.modGen..cctor() in H:\WorkSpace\CHKTRK\CHKTRK\CHKTRKClasses\Mod\modGen.vb:line 138
       InnerException: 

是否有问题我在app.config文件中声明连接字符串的方式,或使用检索它的方法?

Is there something wrong with the way I declare my connection string in the app.config file, or with the method that retrieves it ?

推荐答案

添加连接字符串到asp.net应用程序的 web.config

Add the connection string to the web.config of your asp.net application.

您可以根据此处

这篇关于无法从app.config获取连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆