c# – asp.net mvc核心如何返回Json查询

首先,我知道如何通过执行此操作返回Json查询

public JsonResult streams()
{
    using (var conn = new NpgsqlConnection(Connectionstring))
    {
        conn.Open();
        var credentials =  conn.Query<Streams>("select id,name from streams").ToList();                
        ViewData["Message"] = "Your application description page.";
        conn.Close();
        return Json(credentials);
    }
}

上面的代码从数据库中为我返回Json,但是现在我实际上是通过将查询更改为此来从SQL代码返回Json

var credentials =  conn.Query<Streams>("select SELECT array_to_json(array_agg(t)) from (select id,name from streams) t").ToList();

新查询正常工作,但它在Controller中返回null,因为我现在已经这样了

public JsonResult streams()
{
    using (var conn = new NpgsqlConnection(Connectionstring))
    {
        conn.Open();
        var credentials =  conn.Query<Streams>("SELECT array_to_json(array_agg(t)) from (select id,name from streams) t").ToList();            
        ViewData["Message"] = "Your application description page.";
        conn.Close();
        return Json(credentials);
    }
}

我怎样才能解决这个问题 ?我的假设是使用JsonResult并将Json作为动作返回是搞乱的事情,因为SQL查询已经返回Json.

这是我的Stream Class

  public class Streams
    {
        [Key]
        public int id { get; set; }
        public string name { get; set; }
        public int profile_id { get; set; }

        public DateTime created_on { get; set; }
        public int last_reply { get; set; }
        public int comments { get; set; }
        public string city { get; set; }
        public string state { get; set; }
        public float latitudes { get; set; }
        public float longitudes { get; set; }
        public int votes { get; set; }
    }

最佳答案 这是因为你的字符串中有Json,而对this.Json(object)的调用是为了将它序列化为Json而设计的.

在MVC 5中,您可以:

return this.Content(credentials, "application/json");

ContentResult类在MVC Core中,所以我假设语法保持不变.

点赞