简体   繁体   English

尝试从web.config获取连接字符串时抛出NullReferenceException

[英]NullReferenceException thrown when attempting to get connectionstring from web.config

I am trying to implement NLayering in my asp.net mvc 5 application and have separated the application into different layers, one being the data access layer(DAL). 我试图在我的asp.net mvc 5应用程序中实现NLayering,并将该应用程序分为不同的层,其中之一是数据访问层(DAL)。 In my DAL when I try to access the connection string in my Insert method I get a NullReferenceException. 在我的DAL中,当我尝试在Insert方法中访问连接字符串时,出现了NullReferenceException。 I have added the System.Configuration reference to my DAL project and a web.config file containing the ff code. 我已经将System.Configuration参考添加到我的DAL项目中,并添加了一个包含ff代码的web.config文件。

web.config web.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
<add name="JcSpaceConnectionString" connectionString="Data Source=localhost;Initial Catalog=JcSpaceDatabase;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>

JcSpaceDAL.cs JcSpaceDAL.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using JcSpaceEntities;

namespace JcSpaceDAL
{
    public class JcSpaceDAL
    {

        public static void Insert(JcSpaceAccount accountInfo)
        {
            string connectionString =    ConfigurationManager.ConnectionStrings["JcSpaceConnectionString"].ConnectionString;//This line causes the nullreferenceexception
            SqlConnection conn;
            SqlCommand cmd;
            using (conn = new SqlConnection(connectionString))
            using (cmd = new SqlCommand("spInsert")) {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Name",   accountInfo.FirstName.ToString()+""+ accountInfo.LastName.ToString());
                cmd.Parameters.AddWithValue("@Email", accountInfo.Email);
                cmd.Parameters.AddWithValue("@DateOfBirth", acco    untInfo.DateOfBirth);
                cmd.ExecuteNonQuery();
            }


        }
    }
}

Why does it cause this? 为什么会导致这种情况?

I am guessing that you added the JcSpaceConnectionString to the wrong web.config file. 我猜您将JcSpaceConnectionString添加到了错误的web.config文件中。 Did you add the web.config file to your DAL project? 您是否已将web.config文件添加到DAL项目中? If so you'll need to move it to the MVC project instead. 如果是这样,则需要将其移至MVC项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM