WebService上篇:实现业务接口

xiaoxiao2021-02-28  98

WebService

Web Service也叫XML Web Service WebService是一种可以接收从Internet或者Intranet上的其它系统中传递过来的请求,轻量级的独立的通讯技术。下面是如何编写一个简单的webservice业务接口程序(此处使用的语言为C#)。

*Webservice传递的数据只能是序列化的数据,典型的就是xml数据*

1. 构建项目 新建一个ASP.NET空Web应用程序

在Web程序上建一个Web服务

2. 实现接口(这里我把一个表的数据以xml的形式导出)

下面从数据库中返回一个DataSet

<!-- web.config中配置数据库 --> <connectionStrings> <add name="db_test" connectionString="Data Source=主机名;Initial Catalog=数据库名; User ID=用户名;Password=密码;pooling=true;max pool size=200" providerName="System.Data.SqlClient"/> </connectionStrings> //DBhelper中执行查询的方法,返回一个DataSet public static DataSet GetDataSet(string sql) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); SqlCommand cmd = new SqlCommand(sql, connection); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds); return ds; } }

将DataSet转换成一个XmlDocument对象

/// <summary> /// 将DataSet转成XmlDocument /// </summary> /// <param name="ds"></param> /// <returns></returns> public static XmlDocument ConvertDataSetToXML2(DataSet ds) { XmlDocument doc = new XmlDocument(); XmlNode node = doc.CreateXmlDeclaration("1.0","utf-8","yes"); doc.AppendChild(node); //增加根节点 XmlElement rootElm = doc.CreateElement("FIELD"); doc.AppendChild(rootElm); foreach (DataRow row in ds.Tables[0].Rows) { XmlElement rootContent = doc.CreateElement("CONTENT_KEY_VALUE"); rootElm.AppendChild(rootContent); foreach (DataColumn dc in ds.Tables[0].Columns) { XmlElement subElm = doc.CreateElement(dc.ColumnName); subElm.InnerText = ds.Tables[0].Rows[0][dc.ColumnName].ToString(); rootContent.AppendChild(subElm); } } return doc; }

WebService接口

[WebMethod(Description = "查询数据")]//必须要有这个标志 public XmlDocument GetMessageData() { try { XmlDocument xd = new XmlDocument(); DataSet ds = DBHelper.GetDataSet("select * from TFD_DGNDrawingAndTFD"); if (ds != null && ds.Tables.Count > 0) { xd = XmlUtil.ConvertDataSetToXML2(ds); return xd; } else { return xd; } } catch (Exception) { return null; } }

3. 运行结果

转载请注明原文地址: https://www.6miu.com/read-77010.html

最新回复(0)