【问题标题】:MongoDB C# Driver failed to run database command authenticateMongoDB C# 驱动程序无法运行数据库命令验证
【发布时间】:2016-12-21 23:00:44
【问题描述】:

我想使用 C# 向 MongoDB 进行身份验证,而不是通过在 MongoClient() 实例上传递连接字符串/凭据。就像我们在 MongoDB Shell 上做的一样,我们调用 monog -> db.auth(<username>,<password>) 表示先连接数据库,然后进行身份验证。

  1. 编写 C# 代码
    这是我的代码:

    var mongoClient = new MongoClient();
    var testDB = mongoClient.GetDatabase("test");
    
    string username = txtUserName.Text;
    string password = txtPassword.Password;
    
    // Check password
    var cmd = new BsonDocument("authenticate", new BsonDocument
    {
        {"username",username },
        {"password",password }
    });
    
    var queryResult = testDB.RunCommand<BsonDocument>(cmd);
    

    我的代码连接到 MongoDB 并调用 authenticate 数据库命令 (described Here. It's not the db.auth() Shell method) 以使用它登录

  2. 使用 --auth 选项运行 MongoDB。

  3. 运行我的代码。

在第 3 步之后,我遇到了这个问题。我的代码说

附加信息:命令验证失败:接收到的验证命令中缺少字段/类型错误。

我已阅读 MongoDB 文档(还有我在上面添加的链接)我找不到我缺少的东西。

【问题讨论】:

  • db主机名和url在哪里???
  • 默认连接到 localhost:27017。我们不需要指定主机名。
  • 哦.. Okies.. 谢谢.. 我不熟悉 c# 驱动程序连接。在 Java 中,我们必须使用 ServerAddress 类指定主机名和 url。认为它会在 C# 中类似

标签: c# mongodb authentication mongodb-.net-driver


【解决方案1】:

我认为你可以使用JsonCommand 调用eval 函数来执行db.auth 这样的函数-未测试-:

var command = new JsonCommand<BsonDocument>(@"{ eval: ""db.auth(\""username\"", \""password\"");"" }");
var result = db.RunCommand(command);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-06
    • 2011-10-09
    • 2023-04-06
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多