连接到mongodb的web api未返回正确的json

连接到mongodb的web api未返回正确的json,mongodb,asp.net-web-api,Mongodb,Asp.net Web Api,我尝试创建一个web api,在一次测试中,我尝试连接到mongodb数据库并返回结果,我希望abel不仅从.net客户端使用此web api,而且从html页面使用此web api public class Default1Controller : ApiController { public IMongoCollection<Category> Get() { MongoClient client = new Mon

我尝试创建一个web api,在一次测试中,我尝试连接到mongodb数据库并返回结果,我希望abel不仅从.net客户端使用此web api,而且从html页面使用此web api

public class Default1Controller : ApiController
    {
        public IMongoCollection<Category> Get()
        {
            MongoClient client = new MongoClient();

            var db = client.GetDatabase("local");
            var collection = db.GetCollection<Category>("category");
            List<Category> model = (from contact in collection
                                    select new Category
                    {
                        id = contact["_id"].AsString,
                        name = contact["name"].AsString,
                        datecreated = contact["String"].AsString
                    }).ToList();
            return collection;
        }

如果您使用的是旧的同步驱动程序,那么您需要调用FindAll方法。因为您使用的是WebApi控制器,所以只需返回FindAll方法返回的可枚举数据集合。然后将返回的可枚举项转换为类别对象列表:

public class Default1Controller : ApiController
{
    public IEnumerable<Category> Get()
    {
        MongoClient client = new MongoClient();
        var db = client.GetDatabase("local");
        List<Category> model = new List<Category>();
        var categoryList = db.GetCollection<Category>("category").FindAll().AsEnumerable();
        model = (from category in contactsList
                    select new Category
                    {
                        id = category["_id"].AsString,
                        name = category["name"].AsString,
                        datecreated = category["String"].AsString
                    }
                ).ToList();
        return model;            
    }
}

你没有说你想得到什么,但在我看来,你的get方法应该返回模型,而不是集合。不,我没有可用的FindAll方法。看起来我正在使用新的驱动程序,实际上没有方法可以返回可枚举的内容
public class Default1Controller : ApiController
{
    public IEnumerable<Category> Get()
    {
        MongoClient client = new MongoClient();
        var db = client.GetDatabase("local");
        List<Category> model = new List<Category>();
        var categoryList = db.GetCollection<Category>("category").FindAll().AsEnumerable();
        model = (from category in contactsList
                    select new Category
                    {
                        id = category["_id"].AsString,
                        name = category["name"].AsString,
                        datecreated = category["String"].AsString
                    }
                ).ToList();
        return model;            
    }
}