在做webservice方法时,一般的返回值类型都是string,xml,json.这些通用性比较强的数据类型.根据soap协议,跨平台调用时都是以xml或者json进行数据集的返回.现在我们来验证一下使用datatable能否正常的进行返回.
1.假设我们使用SqlDataAdapter的fill方法 来动态的填充datatable.这样我们在数据列绑定时,只需要调整SQL就能实现数据.
代码如下:

1 public static DataTable GetDataTable(string strSql, DataTable dt) 2 { 3 try 4 { 5 string strCon = System.Configuration.ConfigurationManager.ConnectionStrings["MicroBaseLibrary"].ConnectionString; 6 using (SqlConnection con = new SqlConnection(strCon)) 7 { 8 con.Open(); 9 SqlDataAdapter adapter = new SqlDataAdapter(); 10 adapter.SelectCommand = new SqlCommand(strSql, con); 11 adapter.Fill(dt); 12 con.Close(); 13 return dt; 14 } 15 } 16 catch (ErrorException ex) { throw ex; } 17 catch (Exception ex) { Helpers.LogError(ex); throw ex; } 18 19 } 20 public static string GetSelectSqlByXml(string XmlName) 21 { 22 try 23 { 24 25 XmlDocument xmlDoc = new XmlDocument(); 26 xmlDoc.Load(System.Web.HttpContext.Current.Server.MapPath("~/LogicalLayer/GetDataTableBySql.xml")); 27 XmlNode node = xmlDoc.SelectSingleNode("/Sqlxml/strSql[@name='" + XmlName + "']"); 28 if (node == null) throw new Exception("不存在该节点"); 29 return node.InnerText.Replace("\n", "").Replace("\r", ""); 30 } 31 catch (ErrorException ex) { throw ex; } 32 catch (Exception ex) { Helpers.LogError(ex); throw ex; } 33 34 } 35 /// <summary> 36 /// 用户登录 37 /// </summary> 38 /// <param name="account">用户名</param> 39 /// <param name="password">密码</param> 40 /// <param name="ip">客户端IP</param> 41 /// <returns></returns> 42 [WebMethod] 43 public DataTable CheckPwd(string account, string password, string ip) 44 { 45 46 try 47 { 48 49 50 if (string.IsNullOrEmpty(account)) throw new Exception("请输入用户名"); 51 if (string.IsNullOrEmpty(password) && password.Length<32) throw new Exception("密码格式错误"); 52 string strSql = SqlHelp.GetSelectSqlByXml("CheckPwd"); 53 DataTable dt = new DataTable(); 54 return SqlHelp.GetDataTable(strSql, dt); 55 } 56 catch (Exception ex) 57 { 58 59 throw ex; 60 } 61 62 63 }
简单说明一下: GetSelectSqlByXml 只是我用来读取动态配置sql的方法.以XML文件为例.
代码层面按照逻辑,已经完成.那么下面我新建一个简单的winform程序进行webservice方法调用,验证是否能够正常的返回.数据显示方面,我则使用dataGridView进行展示.
button1的按钮触发代码如下:

1 private void button1_Click(object sender, EventArgs e) 2 { 3 try 4 { 5 datatable_test.Iwin.IWinService test = new datatable_test.Iwin.IWinService(); 6 test.Url = "http://localhost:8005/IWinService.asmx"; 7 DataTable dt = test.CheckPwd("a", "E10ADC3949BA59ABBE56E057F20F883E", ""); 8 dataGridView1.DataSource = dt; 9 //dataGridView1.DataBindings. 10 11 } 12 catch (Exception) 13 { 14 15 throw; 16 } 17 18 }
那么这个时候,就会暴露出第一个问题了.在接受值时,会返回异常.
此时就涉及到webservice的一个序列化生成规则了.在datatable中,其实是有数据的,根据SQL查询出来的数据正常的fill到了datatable中.
为了解决这个问题,我进行了一些调查和验证.这里就不一一描述了,直接上可以正常使用的正确代码.其实改动点很小,明白原理之后,才发现这些问题一开始就应该发现的.
其实只需要在申明datatable时,进行一下初始化定义.在反申明序列化时.底层代码就会进行对应解析了.
相关的webservice使用和常见问题,会在后续调试过程中进行整合.然后进行博客回复.