简体   繁体   中英

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). In my DAL when I try to access the connection string in my Insert method I get a NullReferenceException. I have added the System.Configuration reference to my DAL project and a web.config file containing the ff code.

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

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. Did you add the web.config file to your DAL project? If so you'll need to move it to the MVC project instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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