Jc Balantakbo Jc Balantakbo - 1 year ago 101
ASP.NET (C#) Question

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.


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


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);


Why does it cause this?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download