【问题标题】:json response through MongoDb通过 MongoDb 的 json 响应
【发布时间】:2020-03-19 12:33:14
【问题描述】:

当通过 API 调用下面的 API 方法时

        public IActionResult FirstStudent()
        {
         var collection = this.database.GetCollection<BsonDocument>("students");
            var filter = Builders<BsonDocument>.Filter.Eq("RollNo", "1");
            var document = collection.Find(filter).First();          
            var firstStudent= document.ToJson();
            return Ok(firstStudent);
        }

响应的 Content-Type 为 text/plain。 我需要 Content-Type 作为 application/json。

有什么建议吗?

【问题讨论】:

  • 试试return JsonResult(firstStudent)
  • 我收到错误:不可调用的成员 'JsonResult' 不能像方法一样使用。
  • 我的错,试试return new JsonResult(firstStudent)
  • 我得到 "{ \"_id\" : \"5e54f99a045dba534831a1a2\", \"RollNo\" : \"1\", \"name\" : \"Johnson\"}"我更想要 { "_id" : "5e54f99a045dba534831a1a2", "RollNo" : "1", "name" : "Johnson"}
  • 在下面添加了一个有效的答案

标签: c# mongodb asp.net-core-webapi mongodb-.net-driver webapi


【解决方案1】:

最简单的做法是创建一个学生模型,然后简单地使用学生模型返回一个 ok 结果,如下所示:

public class Student
{
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    public int RollNo { get; set; }

    public string Name { get; set; }
}
public IActionResult FirstStudent()
{
    var collection = this.database.GetCollection<Student>("Student");
    var filter = Builders<Student>.Filter.Where(s => s.RollNo == 1);
    var document = collection.Find(filter).First();
    return Ok(document);
}

【讨论】:

  • 我无法创建类,参数可能会动态变化。还有其他解决方案吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-12
  • 2014-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-26
相关资源
最近更新 更多