我使用此代码调用 ASP.Net core C# Webservice 来访问 SQL 表:
HttpResponseMessage message2 = client.GetAsync("GetAll?Columns=*&Tbl=Coding_Sell").Result;
string userJson2 = message2.Content.ReadAsStringAsync().Result;
MessageBox.Show(userJson2);
DataTable DT = JsonConvert.DeserializeObject<DataTable>(userJson2);
这是我的网络方法:
[WebMethod]
public string GetAll(string Columns, string Tbl)
{
return ObjdBAccess.Get(Columns, Tbl);
}
及其相关类如下:
public string Get(string Columns, string TableName)
{
String query = "SELECT " + Columns + " From " + TableName;
createConn();
SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
DataSet DS = new DataSet();
adapter.Fill(DS);
DataTable DT = DS.Tables[0];
closeConn();
return JsonConvert.SerializeObject(DS);
}
但是程序在这一行失败了:
DataTable DT = JsonConvert.DeserializeObject<DataTable>(userJson2);
出现以下错误: '解析值时遇到意外字符:<. Path '', line 0, position 0.'
这是我的 userJson2 变量:
<?xml version="1.0" encoding="utf-8"?>
{"表格":[{"Main_Code":51,"Property_Name":"出售","Sub_Code":"1"},{"Main_Code":52,"Property_Name":"出售2","Sub_Code": “2”}]}
请告诉我我的代码有什么问题?
默认情况下,ASP.NET Web 方法以 XML 形式返回响应。您应该修改响应,使其以 JSON 形式返回:
[WebMethod]
public static void GetAll(string Columns, string Tbl)
{
HttpContext.Current.Response.ResponseType = "application/json";
HttpContext.Current.Response.Write(ObjdBAccess.Get(Columns, Tbl));
HttpContext.Current.Response.End();
}