'System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null
I'm trying create and save the password both in salt and hash while I'm trying to insert user password in database. While I'm clicking the register button it's shows the following error.
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null.
Below I've added my code of registration page.
public class GenerateHash
{
public string CreateSalt(int SaltSize)
{
var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
byte[] Salt = new byte[SaltSize];
rng.GetBytes(Salt);
return Convert.ToBase64String(Salt);
}
public string GenarateHash(string UserPassword, string salt)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(UserPassword + salt);
byte[] PasswordHash = new System.Security.Cryptography.SHA256Managed().ComputeHash(bytes);
return Convert.ToBase64String(PasswordHash);
}
protected void Regist_Click(object sender, EventArgs e)
{
GenerateHash HashAndSalt = new GenerateHash();
string GetSalt = HashAndSalt.CreateSalt(10);
string hashString = HashAndSalt.GenarateHash(Password.Text, GetSalt);
string username = UserName.Text;
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand("Insert into [User](UserName, PasswordHashed, Salt) values(" + "@UserName, @PasswordHashed, @Salt)", conn))
{
cmd.Parameters.AddWithValue("@UserName", username);
cmd.Parameters.AddWithValue("@PasswordHashed", hashString);
cmd.Parameters.AddWithValue("@Salt", GetSalt);
cmd.ExecuteNonQuery();
}
}
Response.Redirect("Login .aspx");
}
}
Solution 1:[1]
Check the connection string name in your web.config file and see if it matches the ConnectionString in your code.
For example:
<connectionStrings>
<add name="connStr" connectionString="SERVER=localhost;DATABASE=saha;UID=root;PASSWORD=abc123;max pool size=50000000; Allow User Variables=True"/>
</connectionStrings>
So in the above code change the name="connstr" to name="connectionString". I think that should resolve your issue.
Hope it helps.
Solution 2:[2]
Normally, you would try to read a connection string from Web.Config by using its name:
<connectionStrings>
<add name="StudentConn" connectionString="Database=XXX;Data Source=XXX;Initial Catalog=XXX;Integrated Security=True"/>
Gets the connection string for the Logging database
public static string Logging { get { return ConfigurationManager.ConnectionStrings["StudentConn"].ConnectionString; } }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | prkash |
| Solution 2 | Paresh Mangukiya |
