關(guān)于什么是
Web Service,相信在很多地方都會有介紹。簡單的講,
Web Service就是為Web應(yīng)用程序之間彼此共享資源提供了一種可能。采取的方式是將相應(yīng)的類及其中的方法暴露出來,然后調(diào)用者就可以直接調(diào)用這些類中的方法,達(dá)到訪問遠(yuǎn)程資源的目的。本文只是想告訴,如果去使用
Web Service。我主要從服務(wù)器端訪問
Web Service、客戶端訪問
Web Service兩方面來介紹。如果你還不會使用
Web Service,希望對你有所幫助。
一、服務(wù)器端訪問Web Service 這也是
Web Service最適宜的調(diào)用環(huán)境。我們只需知道一個遠(yuǎn)程
Web Service的URL,然后我們就可以直接使用Wsdl工具或更方便的添加Web 引用的方法,將遠(yuǎn)程
Web Service(指.asmx文件)中對應(yīng)類生成一個強(qiáng)類型的本地化代理。通過這個代理,我們就可以像使用本地方法一樣,去調(diào)用這個遠(yuǎn)程類中的方法。使用的過程是非常的簡單。下面讓我們看看具體的操作。
1、新建一個Web Service 選擇asp.net Web服務(wù)模板,然后你會看到VS已經(jīng)自動為我們生成了一個
Web Service的示例代碼。
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
public Service()
{
//如果使用設(shè)計的組件,請取消注釋以下行
//InitializeComponent();
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
一個
Web Service的主要部分VS已經(jīng)幫我們寫好了。這里有幾個地方,我大概說一下。[WebService(Namespace =
http://tempuri.org/)]特性部分,它聲明了
Web Service所對應(yīng)的XMl文件的命名空間,如果你直接瀏覽
Web Service文件,它會出現(xiàn)在XML文件的命名空間聲明中。還是建議修改一下Namespace,雖然它只是一個URI。比如你可以把它改為Namespace=
http://ruihua.cnblogs.com/。[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]特性聲稱的是本
Web Service所應(yīng)符合的Web服務(wù)互操作性規(guī)范,一般情況下我們無需考慮這個,只有某些操作與這個規(guī)范不相符的時候,我們就需要修改ConformsTo = WsiProfiles.None。(比如BasicProfile1_1規(guī)范并不支持方法的重載,如果你有重載方法的話,就需要修改它。)需要特別說明的是,通常一個
web Service文件對應(yīng)的只有一個類,當(dāng)然并不是說你不可以在一個.asmx文件中寫多個類,但只有與WebService指令中的className值對應(yīng)的那個類才會被公開。而對于類中的方法,我們必須顯式加上[WebMthod]特性,才能被公開,這點與類不同。讓我們看一下WebMethod特性的一些其它屬性:
屬性 | 功能 | 示例 |
BufferResponse | 設(shè)置為True時,XML Web服務(wù)的響應(yīng)就保存在內(nèi)存中,并發(fā)送為一個完整的包。如果該屬性設(shè)置為False,則響應(yīng)在服務(wù)器上構(gòu)造的同時,會發(fā)送給客戶機(jī)。 | [WebMethod(BufferResponse=true)] |
CacheDuration | 指定響應(yīng)在系統(tǒng)的高速緩存中的保存時間(秒),默認(rèn)值為0,表示禁用高速緩存。把XML Web服務(wù)的響應(yīng)放在高速緩存中,會提高Web服務(wù)的性能。 | [WebMethod(BufferResponse=true,CacheDuration=30)] |
Description | 對在XML Web服務(wù)的測試頁面上顯示的Web Method應(yīng)用文本的描述。 | [WebMethod(Description="該方法用于獲取一個簡單的字符串")] |
EnableSession | 設(shè)置為True時,會激活Web Method的會話狀態(tài),其默認(rèn)值為False。 | [WebMethod(EnableSession=true)] |
MessageName | 給Method指定一個唯一的名稱,如果要使用重載的Web Method,則必須指定。 | [WebMethod(MessageName="Method1")] |
TransactionOption | 為Web Method指定事務(wù)的支持,其默認(rèn)值為Disbled。如果Web Method是啟動事務(wù)的根對象,Web服務(wù)就可以用另一個需要事務(wù)處理的WebMethod參與事務(wù)處理。其值可以是NotSupported、 Supported、Required和RequiresNew。 | [WebMethod(TransactionOption=System.EnterpriseServices.TransactionOption.Supported)] |
我們修改一下上述代碼。
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
public class Service : System.Web.Services.WebService
{
public Service()
{
}
[WebMethod]
public string Hello(string name)
{
return string.Format("Hello,{0}!Current Time is :{1}", name, DateTime.Now.ToString());
}
}
程序很簡單,傳進(jìn)去一個姓名,返回一串提供信息,下面我們來看一下如何使用這個
Web Service.
2、訪問Web Service 首先需要說明一下,為何我們能夠在本地服務(wù)器上訪問到遠(yuǎn)程服務(wù)器的
Web Service?無論是使用添加Web引用的方式還是使用Wsdl工具,最終的結(jié)果都是生成了一個遠(yuǎn)程
Web Service中類的強(qiáng)類型化本地代理。然后我們是通過這個代理來實現(xiàn)訪問遠(yuǎn)程資源訪問的。下面我們看看怎么通過這兩種方式來實現(xiàn)。
首先我們新建一個新的Web應(yīng)用程序 方式一:使用添加Web 引用。在解決方案資源管理器中單擊右鍵,選擇添加Web 引用...,如下所示:
在URL部分你可以直接輸入遠(yuǎn)程
Web Service的URL,當(dāng)然如果引用的
Web Service來自本地,你可以單擊相應(yīng)的鏈接,然后進(jìn)行選擇。在Web引用名中,填入你自定義的名稱。注意,這個名稱就代指
Web Service的命名空間。在訪問的時候,我們必須通過這個名稱才能引用到
Web Service中的類。填好后,單擊添加引用即可。
為了保證本地測試方便,請將
Web Service所在網(wǎng)站設(shè)為Web 共享,這樣我們就不必考慮在Web引用中加入端口號才能訪問的問題。添加Web引用對話框中查找的實際是WSDL文件,Microsoft的XML Web服務(wù)會根據(jù).asmx文件自動生成wdsl文件。當(dāng)然,我們也可以根據(jù).asmx文件在瀏覽器中打開wsdl文件,按如下路徑:
http://localhost/WebService/Service.asmx?wsdl
接下來,你會看到VS已經(jīng)為我們添加好了Web 引用。
同時在Web.Config文件中也包含了對Web服務(wù)的引用,如下所示:
<appSettings>
<add key="ServiceNamespace.Service" value="http://localhost/WebService/Service.asmx"/>
</appSettings>
接下來,讓我們看一下如何使用這個
Web Service,請看代碼:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ServiceNamespace.Service ws = new ServiceNamespace.Service();
Response.Write(ws.Hello("Ruihua"));
}
}
你會看到,使用遠(yuǎn)程方法就像使用本地方法一樣簡單,下面是運(yùn)行結(jié)果:
原因是:
Web Service不允許我們以匿名的方式訪問。你可以在IIS信息服務(wù)中
Web Service所在站點開啟這項功能。然后,你就可以看到正確結(jié)果了:
方式二:使用WSDL工具。
我們也可以使用VS自帶的wsdl工具來實現(xiàn)相同的功能,這個工具可以將wsdl文件生成在本地生成一個強(qiáng)類型的類文件,然后我們可以就可以直接在項目中使用這個類文件,來訪問遠(yuǎn)程資源。打開VS命令提供,輸入以下命令,如下圖所示:
同時在
C:\ProgramFiles\Microsoft Visual Studio 8\VC下會自動生成一個Service.cs的文件。我們將這個文件置于我們的項目中,就可以直接使用了。
Microsoft(R) Web Services 描述語言實用工具
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Copyright (C) Microsoft Corporation. All rights reserv
wsdl.exe -
使用 ASP.NET,根據(jù) WSDL 協(xié)定文件、XSD 架構(gòu)和 .disc
發(fā)現(xiàn)文檔,為 Xml Web Services 客戶端和 Xml Web Ser
代碼的實用工具。此工具可以與 disco.exe 一起使用。
wsdl.exe <選項> <URL 或路徑> <URL 或路徑>
- 選項 -
<URL 或路徑> -
指向 WSDL 協(xié)定、XSD 架構(gòu)或 .discomap 文檔的 URL 或
/nologo
取消顯示版權(quán)標(biāo)志。
/language:<language>
用于生成的代理類的語言。請從“CS”、“VB”、“JS”
“CPP”中選擇,或者為實現(xiàn) System.CodeDom.Compiler.
的類提供一個完全限定的名稱。默認(rèn)語言為“CS”(CShar
縮寫形式為“/l:”。
/sharetypes
打開類型共享功能。此功能針對不同服務(wù)之間共享
的相同類型(命名空間、名稱和網(wǎng)絡(luò)簽名必須相同)
創(chuàng)建一個具有單一類型定義的代碼文件。
請使用 http:// URLs 作為命令行參數(shù)來引用
服務(wù),或為本地文件創(chuàng)建一個 discomap 文檔。
/verbose
指定 /sharetypes 開關(guān)時顯示額外信息。
縮寫形式為“/v”。
/fields
生成字段而非屬性??s寫形式為“/f”。
/order
為粒子成員生成顯式順序標(biāo)識符。
/enableDataBinding
在所有生成的類型上實現(xiàn) INotifyPropertyChanged 接口
以啟用數(shù)據(jù)綁定??s寫形式為“/edb”。
/namespace:<namespace>
生成的代理或模板的命名空間。默認(rèn)命名空間
為全局命名空間??s寫形式為“/n:”。
/out:<fileName|directoryPath>
生成的代理代碼的文件名或目錄路徑。默認(rèn)文件名是從
服務(wù)名派生的。縮寫形式為“/o:”。
/protocol:<protocol>
重寫要實現(xiàn)的默認(rèn)協(xié)議。請從“SOAP”、“SOAP12”、
“HttpGet”、“HttpPost”中選擇。
/username:<username>
/password:<password>
/domain:<domain>
連接到要求身份驗證的服務(wù)器時使用的憑據(jù)。
縮寫形式為“/u:”、“/p:”和“/d:”。
/proxy:<url>
用來處理 HTTP 請求的代理服務(wù)器的 URL。
默認(rèn)為使用系統(tǒng)代理服務(wù)器設(shè)置。
/proxyusername:<username>
/proxypassword:<password>
/proxydomain:<domain>
連接到要求身份驗證的代理服務(wù)器時使用的憑據(jù)。
縮寫形式為“/pu:”、“/pp:”和“/pd:”。
/appsettingurlkey:<key>
在代碼生成中用來讀取 URL 屬性的
默認(rèn)值的配置項。默認(rèn)為不從配置
文件中讀取。縮寫形式為“/urlkey:”。
/appsettingbaseurl:<baseurl>
計算 URL 段時使用的基 URL。
還必須指定 appsettingurlkey 選項。URL 段是
從 appsettingbaseurl 計算
WSDL 文檔中的 URL 的相對 URL 的結(jié)果。縮寫形式為“
/parsableerrors
輸出錯誤,其格式與編譯器報告的格式類似。
- 高級 -
/server
服務(wù)器開關(guān)已被否決。請改用 /serverInterface。
使用基于協(xié)定的 ASP.NET,為 Xml Web Services 實現(xiàn)生成抽象類。默認(rèn)情況下,生成
客戶端代理類。
/serverInterface
為 ASP.Net Web 服務(wù)的服務(wù)器端實現(xiàn)生成接口。將為 wsdl 文檔中的每個綁定生成
一個接口。wsdl 單獨實現(xiàn) wsdl 協(xié)定(實現(xiàn)接口的類在類方法上不應(yīng)包括下列任意一項:
更改 wsdl 協(xié)定的 Web 服務(wù)屬性或序列化屬性)??s寫形式為“/si”。
/parameters:<file>
從指定的 xml 文件讀取命令行選項。這樣可以指定命令行中無法使用的選項,例如選擇
生成的異步編程模型類型。有關(guān)詳細(xì)信息,請參閱工具文檔??s寫形式為“/par:”。
//------------------------------------------------------------------------------
// <auto-generated>
// 此代碼由工具生成。
// 運(yùn)行庫版本:2.0.50727.42
//
// 對此文件的更改可能會導(dǎo)致不正確的行為,并且如果
// 重新生成代碼,這些更改將會丟失。
// </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=2.0.50727.42。
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name = "ServiceSoap", Namespace = "http://ruihua.cnblogs.com/")]
public partial class Service : System.Web.Services.Protocols.SoapHttpClientProtocol
{
private System.Threading.SendOrPostCallback HelloOperationCompleted;
/// <remarks/>
public Service()
{
this.Url = "http://localhost/WebService/Service.asmx";
}
/// <remarks/>
public event HelloCompletedEventHandler HelloCompleted;
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://ruihua.cnblogs.com/Hello", RequestNamespace = "http://ruihua.cnblogs.com/", ResponseNamespace = "http://ruihua.cnblogs.com/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string Hello(string name)
{
object[] results = this.Invoke("Hello", new object[] {
name});
return ((string) (results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginHello(string name, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("Hello", new object[] {
name}, callback, asyncState);
}
/// <remarks/>
public string EndHello(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((string) (results[0]));
}
/// <remarks/>
public void HelloAsync(string name)
{
this.HelloAsync(name, null);
}
/// <remarks/>
public void HelloAsync(string name, object userState)
{
if ((this.HelloOperationCompleted == null))
{
this.HelloOperationCompleted = new System.Threading.SendOrPostCallback(this.OnHelloOperationCompleted);
}
this.InvokeAsync("Hello", new object[] {
name}, this.HelloOperationCompleted, userState);
}
private void OnHelloOperationCompleted(object arg)
{
if ((this.HelloCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs) (arg));
this.HelloCompleted(this, new HelloCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
public new void CancelAsync(object userState)
{
base.CancelAsync(userState);
}
}
/**/
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void HelloCompletedEventHandler(object sender, HelloCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class HelloCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal HelloCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState)
:
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public string Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((string) (this.results[0]));
}
}
}