WebService采用HTTP协议传输数据,采用XML格式封装数据。在.Net Core中推荐使用代理类来调用WebService,方便、自动。
引用WS与代理类生成
VS项目 右键 添加 引用服务,输入WS地址,转跳至对应的服务,点击完成生成代理类。也可以使用命令引用。
- dotnet svcutil WebServiceUrl
调用WS接口
- /// <summary>
- /// 预检信息上传(WS)
- /// </summary>
- public bool UploadHspinfo(string xml)
- {
- try
- {
- _Logger.LogInformation("Updload:WS Init");
- BasicHttpBinding binding = new BasicHttpBinding();
- EndpointAddress address = new EndpointAddress(_UploadConfig.WSUrl);
- ServiceReference.DataWebServiceIClient client = new ServiceReference.DataWebServiceIClient(binding, address);
- var res = client.saveB_HspinfoListAsync(xml);
- return res.Result.Body.@return;
- }
- catch (Exception ex)
- {
- _Logger.LogInformation("Updload:WS Error");
- _Logger.LogInformation(ex.ToString());
- return false;
- }
- }
Xml转化
WS采用Xml格式传输数据,在调用第三方WS接口时,需要符合对应数据结构。实体对象转Xml需要对格式处理,比如去除头部声明。下面方法可以获得干净的Xml字符串,方便组装。
- public static string ModelToXml<T>(T model)
- {
- MemoryStream stream = new MemoryStream();
- XmlSerializer serializer = new XmlSerializer(typeof(T));
- XmlWriterSettings settings = new XmlWriterSettings
- {
- Indent = true,
- IndentChars = " ",
- NewLineChars = "\r\n",
- Encoding = Encoding.UTF8,
- OmitXmlDeclaration = true // 不生成声明头
- };
- using (XmlWriter xmlWriter = XmlWriter.Create(stream, settings))
- {
- // 强制指定命名空间,覆盖默认的命名空间
- XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
- namespaces.Add(string.Empty, string.Empty);
- serializer.Serialize(xmlWriter, model, namespaces);
- xmlWriter.Close();
- };
- stream.Position = 0;
- StreamReader sr = new StreamReader(stream);
- string str = sr.ReadToEnd();
- return str;
- }