用.net写web api的时候,返回json

某一天发现web api的接口返回的json字符串(string格式)中,有多余的双引号,百度之后修改OK,代码如下:

public HttpResponseMessage get()
        {
            //建立连接对象  
            SqlConnection cnn = new SqlConnection();
            cnn.ConnectionString = "Initial Catalog=TEST;Data Source=10.0x.5x.2x;User ID=xxxx;Password=xxx;";
            //打开连接  
            cnn.Open();


            string sql = "select khqc,dz from tbl_kh2";

            //建立执行对象  
            SqlCommand cmd = new SqlCommand(sql, cnn);
            DataSet ds = new DataSet();
            SqlDataReader dr = cmd.ExecuteReader();

            ArrayList clients = new ArrayList();
            while(dr.Read())
            {
                Client client = new Client();
                client.nm = dr["khqc"].ToString();
                client.ad = dr["dz"].ToString();
                //client.contact = dr["lxr"].ToString();
                //client.phone = dr["jh"].ToString();

                clients.Add(client);
            }

            cnn.Close();

            string json = JsonConvert.SerializeObject(clients);
            return new HttpResponseMessage { Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") };
        }

修改点只有两个地方:

1. 返回类型修改为HttpResponseMessage 

2. 最后一行返回值类型做了特殊处理。


以此备忘

你可能感兴趣的:(C#/.NET)