asp.net mvc core how can I return a Json query

给你一囗甜甜゛ 提交于 2020-01-02 05:53:21

问题


First and foremost I Know how to return a Json Query by doing this

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);
    }
}

That code above returns Json for me from the database, however now I am actually returning the Json from the SQL code by changing the query to this

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

That new query works correctly however it is returning null in the Controller as I have it like this now

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);
    }
}

How can I fix this ? My assumption is that using JsonResult and returning Json as an action is messing things up because the SQL query is already returning Json.

This is my 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; }
    }

回答1:


It's because you have Json in your string and the call to this.Json(object) is designed to serialize it to Json.

In MVC 5 you could:

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

The ContentResult class is in MVC Core, so I assume that the syntax remains the same.



来源:https://stackoverflow.com/questions/35443521/asp-net-mvc-core-how-can-i-return-a-json-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!