如何在Asp.net MVC3网络应用程序中从web.config读取ConnectionString?

3
我正在使用Asp.net Razor MVC3。 我已创建了一个App_Code文件夹,并在其中创建了一个类,我想从web.config中读取连接字符串并使用此类与数据库交互。 我正在这个app_code类中写入System.Configuration,但它没有显示ConfigurationManagerConfiguration类。看起来像这样enter image description here
如果我将相同的行写入任何控制器中,则会显示System.Configuration.ConfigurationManager,我可以在控制器中从web.config读取连接字符串,但在app_code中我无法这样做。
请告诉我如何在app_code类中读取连接字符串?
2个回答

10

包含对 System.Web.Configuration 的引用:

using System.Web.Configuration;

然后,在您的代码中,像这样访问它:

WebConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;

示例类:

using System.Web.Configuration;

namespace MyWebApp.App_Code
{
    public class TestClass
    {
        public void TestMethod()
        {
            var connStr = WebConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
        }
    }
}

我正在使用Visual Studio2012中的MVC3和Framework4.0进行工作。当我将System.Web.Configuration引用添加到我的MVC应用程序中时,它不会显示在“添加引用管理器”弹出框中。因此,我无法将其引用包含在项目中。 - Gaurav Agrawal
你不能从“添加引用弹出窗口”中添加System.Web.Configuration,你只需要添加System.Web即可。一旦添加了它,你就可以访问System.Web.Configuration命名空间。此外,在你的原始帖子中,你提到了尝试添加“System.Configuration.ConfigurationManager”。但我的答案并没有使用该命名空间。我提到的是System.Web.Configuration。仔细查看我的答案,确保你正在使用正确的命名空间,并使用WebConfigurationManager.ConnectionStrings["connStr"].ConnectionString来获取你的连接字符串。 - M.Ob
我遇到了一个非常奇怪的错误,即当我创建一个空的MVC应用程序时,就会出现这个错误,但如果我创建任何Internet或Intranet MVC应用程序,则不会出现此错误。 - Gaurav Agrawal

0
如果您收到有关“the ConfigurationManager does not exist in the current context”的错误,那么您需要安装dll程序集,并在控制器中添加using System.Configuration语句。
您可以在Nuget gallery中找到它,链接地址在https://www.nuget.org/packages/System.Configuration.ConfigurationManager/,或者在Visual Studio中添加程序集引用。
之后,您可以编写string MyString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;(请注意该代码片段末尾的单数形式)。
如果您还没有为System.Configuration编写使用语句,则可以编写相同的内容,但要在前面加上string MyString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接