如何存储输入数据库表的用户名

时间:2017-06-08 03:21:58

标签: c# sql-server

我正在尝试将登录期间输入的用户名存储在表登录详细信息中。我正在跟踪尝试登录应用程序的用户。我的代码在conn.Open崩溃了。请帮我解决一下这个。提前谢谢。

以下是我在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");

        }

2 个答案:

答案 0 :(得分:1)

将它放在代码的顶部:

使用System.Web.Configuration; 把它放在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);

答案 1 :(得分:0)

您正在使用的连接字符串看起来有问题。

确保传递正确的ServerName和数据库名称。

另外,请仔细检查是否要使用Windows身份验证或在数据库中配置任何用户登录。

您还可以查看以下网址,了解有关连接字符串的更多信息:

https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx

https://www.connectionstrings.com/sql-server/

如果您仍然遇到错误,请在此处分享错误详情。

相关问题