c# - 更改 SqlConnection,Credentials 属性

标签 c# sqlconnection

所以我有一个登录页面,我必须实现一个验证:“如果用户是“sa”,那么它应该使用该用户凭据连接到数据库”,这意味着我必须修改我的 SqlConnection 的凭据。目的:

        if(username.Equals("sa", StringComparison.OrdinalIgnoreCase))
        {
            var securePassword = new System.Security.SecureString();
            foreach(char character in password)
            {
                securePassword.AppendChar(character);
            }

            securePassword.MakeReadOnly();
            var credentials = new SqlCredential(username, securePassword);
            sqlConn.Close();
            sqlConn.Credential = credentials;

            sqlConn.Open();

            return true;
        }

但我在 sqlConn.Credential = credentials; 中遇到异常即使该属性不是 readonly

InvalidOperationException: Cannot use Credential with UserID, UID, Password, or PWD connection string keywords.



有没有其他方法可以改变Credentials属性(property)?

提前致谢。

最佳答案

SqlConnection.Credential 属性
来自 https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.credential(v=vs.110).aspx
将引发 InvalidOperationException 异常:

  • 如果在打开的连接上设置了凭据。
  • 如果在 Context Connection=true 时设置了 Credential。
  • 如果在 Integrated Security = true 时设置了 Credential。
  • 如果在连接字符串使用密码时设置了凭据。
  • 如果在连接字符串使用 UserID 时设置了 Credential。
  • 关于c# - 更改 SqlConnection,Credentials 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36066454/

    相关文章:

    c# - 如果设置了 Min Pool Size,池中连接的生命周期是多少?

    c# - 通过网络连接到 SQLite 数据库

    c# - 是否有不使用连续内存的开源 MemoryStream 实现?

    C# Telnet 实现与 TCPClient,用户名/密码错误

    c# - 为什么不处理/关闭 SqlConnection?

    c# - "Login failed for user"C# 与 SQLConnection

    c# - using 语句可以用大括号代替吗?

    c# - ElasticSearch 嵌套 MatchPhrasePrefix 多个字段

    c# - 使用自定义 ItemsPanel 模板的 WPF ListBox 如何根据其项目的大小调整自身大小

    c# - 用于识别网址的正则表达式