雖然現在已經進入了.NET FrameWork 4.0的時代,WebService也已經逐漸被淘汰,取而代之的是WCF。
但在工作中難免遇到需要兼容舊版本程序和按照以前的文檔進行開發。
一般一個已經實現功能的WebService會發布自己的WSDL文件,供客戶端調用生成代理類。
但有時是先有server與client交互的接口定義(WSDL)文件,然后由server和client端分別寫程序,一個提供web服務,一個使用web服務。
最近,我也遇到了這個問題。由於業務方僅提供了WSDL文件並確定了其規范,需要我們開發服務端供調用。
1、使用VS2010提供的工具wsdl.exe由WSDL文件生成cs文件
使用wsdl.exe的/serverInterface選項(或縮寫的 /si)指定輸入的wsdl文件(注意,如果要轉換的wsdl文件中import了其他wsdl文件,則所有文件都應列出,包括使用到的xsd文件也應列出)。輸出將是 一個代碼文件(默認是C#的,如果需要別的語言,參考MSDN中wsdl.exe的使用說明),其中包含每個 wsdl 綁定的接口。
示例:假設有ServerInterfaceSample.wsdl
wsdl.exe /si ServerInterfaceSample.wsdl
如果使用Service.xsd作為schema文件,則改為
wsdl.exe /si ServerInterfaceSample.wsdl Service.xsd
生成代碼如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
//------------------------------------------------------------------------------
// <auto-generated>
// 此代碼由工具生成。
// 運行時版本:4.0.30319.239
//
// 對此文件的更改可能會導致不正確的行為,並且如果
// 重新生成代碼,這些更改將會丟失。
// </auto-generated>
//------------------------------------------------------------------------------
using
System;
using
System.ComponentModel;
using
System.Diagnostics;
using
System.Web.Services;
using
System.Web.Services.Protocols;
using
System.Xml.Serialization;
//
// 此源代碼由 wsdl 自動生成, Version=4.0.30319.1。
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute(
"wsdl"
,
"4.0.30319.1"
)]
[System.Web.Services.WebServiceBindingAttribute(Name=
"WebServiceSoap"
, Namespace=
"http://tempuri.org/"
)]
public
interface
IWebServiceSoap {
/// <remarks/>
[System.Web.Services.WebMethodAttribute()]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute(
"http://tempuri.org/sendSMS"
, RequestNamespace=
"http://tempuri.org/"
, ResponseNamespace=
"http://tempuri.org/"
, Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
long
sendSMS(InfoHeader header,
string
sessionId,
string
sender,
string
smsContent,
string
receiverList,
string
productCode,
string
pseudoFlag);
}
|
2、使用以上生成的文件進行修改,實現你的WebService方法即可.
