从mongodb获取密码c#

时间:2016-04-21 11:24:23

标签: c# mongodb

我正在尝试创建一个登录方法,我需要从相应的用户那里获取密码。这是我的数据库层代码:

public int loginUser(string userName, string pass)
    {
        int result = 0;
        var credentials = MongoCredential.CreateMongoCRCredential("SearchForKnowledge", userName, pass);
        var settings = new MongoClientSettings
        {
            Credentials = new[] { credentials }
        };
        try
        {
            var mongoClient = new MongoClient(settings);
            var database = mongoClient.GetDatabase("SearchForKnowledge");
            var coll = database.GetCollection<BsonDocument>("Users");

            var filter = Builders<BsonDocument>.Filter.Eq("userName", userName);
            var query = coll.Find(filter);
            //??????????
        }
        catch (Exception ex) {
            result = 0;
        }
        return result;
    }

你可以看到登录是否成功我试图返回1并且如果失败,则为0(用于重定向目的)。我正在努力检查用户名是否匹配设置的密码。目前我刚刚制作了一个过滤器,将其传递给方法Find并且此时死了。如何从mongodb返回该用户的密码并将其与作为参数传递的密码进行比较?

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

public int loginUser(string userName, string pass)
    {
        int result = 0;
        //Here you use credentials for the connection, not the one passed
        //to the method:
        var credentials = MongoCredential.CreateMongoCRCredential("SearchForKnowledge", connectionUsername, connectionPass);
        var settings = new MongoClientSettings
        {
            Credentials = new[] { credentials }
        };
        try
        {
            var mongoClient = new MongoClient(settings);
            var database = mongoClient.GetDatabase("SearchForKnowledge");
            var coll = database.GetCollection<BsonDocument>("Users");

            var filter = Builders<BsonDocument>.Filter.Eq("userName", userName);
            var result = await coll.Find(filter).ToListAsync().First();
            if(result["Password"] == pass)
            {
               result = 1;
            }
        }
        catch (Exception ex) {
            result = 0;
        }
        return result;