Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用json和webapi显示数据库中的内容_C# - Fatal编程技术网

C# 如何使用json和webapi显示数据库中的内容

C# 如何使用json和webapi显示数据库中的内容,c#,C#,我是webapi新手。我正在使用webapi中的数据表从数据库中获取数据。我想将此数据作为json数组传递 我该怎么做?任何帮助都是值得的 public class theatresController: ApiController { [HttpGet] public static DataTable GetAlltheatredet() { try { string connString = "Server=localhost;dat

我是webapi新手。我正在使用webapi中的数据表从数据库中获取数据。我想将此数据作为json数组传递

我该怎么做?任何帮助都是值得的

public class theatresController: ApiController {

    [HttpGet]
    public static DataTable GetAlltheatredet() {
        try {
            string connString = "Server=localhost;database=mytable;uid=root;";
            string query = "SELECT TheatName FROM `mytable`.`theatredetails`";
            MySqlDataAdapter ma = new MySqlDataAdapter(query, connString);
            DataSet DS = new DataSet();
            ma.Fill(DS);
            return DS.Tables[0];
        } catch (MySqlException e) {
            throw new Exception(e.Message);
        }
    }
}

接下来要做什么?

这可以通过两种简单的方式来完成,一种是使用StringBuilder类,另一种是使用Json.NET汇编 参考:

使用Newtonsoft.json:

    SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=DbEmployee;Integrated Security=SSPI;");
    SqlCommand cmd = new SqlCommand("Select * from tbl_EmpDetails", con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    string JSONresult;
    JSONresult = JsonConvert.SerializeObject(dt);  
    Response.Write(JSONresult);

默认情况下,
json
将传递给客户端。您使用的客户端是什么?
Javascript
.Net
?您需要发出
HTTP
请求才能在客户端获取它。对于
javascript
JQuery
发出
ajax
请求。对于
.Net
客户端,使用
HttpWebRequest
对象。序列化
DataTable
会附带一些不必要的属性,除非否则处理。