Reputation: 303
I am trying to store username entered during login in the table Login Details. I am keeping track of users trying to login into the application. My code crashes at conn.Open. Please help me with this. Thanks in advance.
Here is the code I have written in Homecontroller:
public ActionResult Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var wwid = ActiveDirectoryUserHelper.returnWWid(model.UserName, model.UserName.Substring(model.UserName.IndexOf("\\")+1), model.Password);
if(wwid==null)
{
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
else
{
Session["UserId"] = model.UserName.Substring(model.UserName.IndexOf("\\") + 1);
Session["UserPassword"] = model.Password;
ViewBag.userId = Crypto.EncryptData(model.UserName.Substring(model.UserName.IndexOf("\\") + 1));
ViewBag.pwd = Crypto.EncryptData(model.Password);
}
SqlConnection conn = new SqlConnection(@"data source = XYZ,1433;initial catalog=Application;integrated security=True");
string sql = "INSERT INTO LoginDetails (username) values (@username)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@username", System.Data.SqlDbType.VarChar, 50).Value = model.UserName;
//cmd.Parameters["@username"].Value = model.UserName;
cmd.ExecuteNonQuery();
return View("Management");
}
Upvotes: 0
Views: 193
Reputation: 446
Put this at the top of your code:
using System.Web.Configuration; Put this in Web.Config:
<connectionStrings >
<add
name="myConnectionString"
connectionString="Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
and where you want to setup the connection variable:
SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
Upvotes: 1
Reputation: 930
It looks like something is wrong with the connection string you are using.
Make sure you are passing correct ServerName and database name.
Also please double check if you want to use Windows Authentication or have any user configured in the database to login with.
You can also check the following URL to know more about the connection string:
https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx
https://www.connectionstrings.com/sql-server/
If you are still facing the error, please share the error detail here.
Upvotes: 0