Code Project - Your First C# Web Service
原文連接:http://www.codeproject.com/cs/webservices/myservice.asp
作者:Chris Maunder
Introduction
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
Creating your first web service is incredibly easy. In fact, by using the wizards in Visual Studio. NET you can have your first service up and running in minutes with no coding.
創(chuàng)建你的第一個web service是難以置信地容易。事實上,通過使用Visual Studio.NET的向?qū)?#xff0c;你可以無需編碼在幾分鐘內(nèi)創(chuàng)建和運行你的第一個Web Service。
For this example I have created a service called MyService in the /WebServices directory on my local machine. The files will be created in the /WebServices/MyService directory.
比如說,我已經(jīng)創(chuàng)建了一個叫做MyService 的service在我本地機器的/WebServices 目錄。文件將被創(chuàng)建在/WebServices/MyService 目錄。
A new namespace will be defined called MyService, and within this namespace will be a set of classes that define your Web Service. By default the following classes will be created:
我們將定義一個新的命名空間叫做MyService,在這個命名空間里會有一些類來定義你的Web Service。默認情況下,一下類將被創(chuàng)建:
| Global (in global.asax) | Derived from HttpApplication. This file is the ASP.NET equivalent of a standard ASP global.asa file. |
| WebService1 (in WebService1.cs) | Derived from System.Web.Services.WebService. This is your WebService class that allows you to expose methods that can be called as WebServices. |
?
| Global (in global.asax) | 繼承自HttpApplication。ASP.NET里的這個文件相當于一個標準ASP global.asa文件 |
| WebService1 (in WebService1.cs) | 繼承自System.Web.Services.WebService. 這是你的WebService類,它允許你展示那些能被叫做WebServices的方法 |
There are also a number of files created:
還有另外一些文件被創(chuàng)建:
| AssemblyInfo.cs | Contains version and configuration information for your assembly. |
| web.config | Defines how your application will run (debug options, the use of cookies etc). |
| MyService.disco | Discovery information for your service. |
| WebService1.asmx | Your WebService URL. Navigate to this file in a browser and you will get back a user-friendly page showing the methods available, the parameters required and the return values. Forms are even provided allowing you to test the services through the web page. |
| bin\MyService.dll | The actual WebService component. This is created when you build the service. |
?
| AssemblyInfo.cs | 包含你的程序集的版本和設(shè)置信息 |
| web.config | 定義你的程序如何運行(調(diào)試選項,cookies的使用等等) |
| MyService.disco | 為你的服務(wù)發(fā)現(xiàn)信息(譯注:我自己新創(chuàng)建的沒發(fā)現(xiàn)這個文件,也許版本不一樣,我的是VS.NET2003) |
| WebService1.asmx | 你的WebService URL。在瀏覽器導(dǎo)航到這個文件,你將得到一個用戶友好的頁面,展示了可用的方法,需要的參數(shù)和返回值。甚至提供了供你在頁面上測試服務(wù)的Forms |
| bin\MyService.dll | 事實上的WebService組件。這是在你建立service的時候創(chuàng)建的。 |
The class for your service that is created by default is called (in this case) WebService1, and is within the MyService namespace. The code is partially shown below.
默認情況下,為你的service創(chuàng)建的類(在我們現(xiàn)在的情況下)叫做WebService1,它是在MyService 命名空間下的。部分代碼如下所示:
{
????
????/**////?<summary>
????///????Summary?description?for?WebService1.
????///?</summary>
????[WebService(Namespace="http://codeproject.com/webservices/",
????????????????Description="This?is?a?demonstration?WebService.")]
????public?class?WebService1?:?System.Web.Services.WebService
????{
????????public?WebService1()
????????{
????????????//CODEGEN:?This?call?is?required?by?the?ASP+?Web?Services?Designer
????????????InitializeComponent();
????????}
????????
????????
????????[WebMethod]
????????public?string?HelloWorld()
????????{
????????????return?"Hello?World";
????????}
????}
}
A default method HelloWorld is generated and commented out. Simply uncomment and build the project.?Hey Presto, you have a walking talking WebService.?
獲得了一個默認的方法HelloWorld 并被注釋起來。簡單地把注釋去掉,建立項目(F5)。
嘿嘿,你已經(jīng)建立運行了一個WebService(原文的語氣自己理解吧 -_-!!)
A WebService should be associated with a namespace. Your Wizard-generated service will have the name space http://tempuri.org. If you compile and run the service as-is you'll get a long involved message indicating you should choose a new namespace, so we add the namespace, and the WebService description as follows:
一個WebService應(yīng)該跟一個命名空間相聯(lián)系。你用向?qū)Й@得的service會有一個叫做http://tempuri.org的命名空間。如果你照現(xiàn)在的樣子編譯運行,你將得到一個很長的相關(guān)信息指出你應(yīng)該選擇一個新的命名空間,所以我們就增加一個命名空間,那么WebService的描述就像下面這樣:
????????????Description="This?is?a?demonstration?WebService.")]
public?class?WebService1?:?System.Web.Services.WebService
{
????
To test the service you can right click on WebService1.asmx in the Solution Explorer in Visual Studio and choose "View in Browser". The test page is shown below,
想測試服務(wù)你只要右鍵點擊資源管理器里的WebService1.asmx ,然后選擇“在瀏覽器中查看”。測試頁面如下所示
When invoked this returns the following:
點擊調(diào)用按鈕返回一下信息:
Getting the demo application to run
If you downloaded the source code with this article then you will need to create a directory 'WebServices' in your web site's root directory and extract the downloaded zip into there. You should then have:
如果你下載了這篇文章的源代碼,那你需要在你的網(wǎng)站的根目錄創(chuàng)建一個'WebServices'目錄,然后把下載的文件解壓到這里。你將得到:
\WebServices
\WebServices\bin
\WebServices\WebService1.asmx
...
Navigating to http://localhost/WebServices/WebService1.asmx won't show you the WebService because you need to ensure that the webservice's assembly is in the application's /bin directory. You will also find that you can't load up the solution file MyService.sln. To kill two birds with one stone you will need to fire up the IIS management console, open your website's entry, right click on the WebServices folder and click Properties. Click the 'Create' button to create a new application the press OK. The /WebServices directory is now an application and so the .NET framework will load the WebService assembly from the /WebServices/bin directory, and you will be able to load and build the MyService.sln solution.
導(dǎo)航到http://localhost/WebServices/WebService1.asmx并不能向你展示WebService,因為你需要保證webservice的程序集在程序的/bin文件夾。你還將大縣你不能載入solution file Myservice.sln。為了一石二鳥,你需要點燃IIS management console(中文版里就是Internet信息服務(wù)),打開你的網(wǎng)站節(jié)點,右擊WebServices文件夾,點擊屬性。點擊’創(chuàng)建’按鈕創(chuàng)建一個新的程序,點確定。/WebServices 文件夾現(xiàn)在是一個程序,那么.NET framework將從/WebServices/bin 文件夾載入WebService程序集,你將能載入和建立MyService.sln solution。(譯注:其實執(zhí)行作者所說的操作以后還是不行,是不是版本不匹配?要想使用下載的代碼,你只要自己建一個WebService,然后把源文件里的“WebService1.cs”文件里的相關(guān)代碼拷貝到你那就行了,然后就可以運行了)
Extending the example
So we have a WebService. Not particularly exciting, but then again we haven't exactly taxed ourselves getting here. To make things slightly more interesting we'll define a method that returns an array of custom structures.
現(xiàn)在我們有了一個WebService。沒什么特別值得激動的,但我們到現(xiàn)在還沒做什么額外的工作(這句話建議還是看原文-_-!!)為了讓這東西稍為有趣一點,我們將定義一個一個方法,返回一個自定義結(jié)構(gòu)的數(shù)組。
Within the MyService namespace we'll define a structure called ClientData:
在MyService命名空間里,我們將定義一個叫做ClientData的結(jié)構(gòu):
????{
????????public?String?Name;
????????public?int????ID;
????}
and then define a new method GetClientData. Note the use of the WebMethod attribute in front of the method. This specifies that the method is accessible as a WebService method.
然后定義一個新的方法GetClientData.注意在方法之前使用WebMethod屬性。這就制定這個方法是一個作為WebsService存取的方法。
[WebMethod]????public?ClientData[]?GetClientData(int?Number)
????{
????????ClientData?[]?Clients?=?null;
????????if?(Number?>?0?&&?Number?<=?10)
????????{
????????????Clients?=?new?ClientData[Number];
????????????for?(int?i?=?0;?i?<?Number;?i++)
????????????{
????????????????Clients[i].Name?=?"Client?"?+?i.ToString();
????????????????Clients[i].ID?=?i;
????????????}
????????}
????????return?Clients;
????}
If we compile, then navigate to the the .asmx page then we are presented with a form that allows us to enter a value for the parameter. Entering a non-integer value will cause a type-error, and entering a value not in the range 1-10 will return a null array. If, however, we manage to get the input parameter correct, we'll be presented with the following XML file:
如果我們編譯,然后導(dǎo)航到擴展名為.asmx的頁面,就展示給我們一個form允許我們輸入一個值作為參數(shù)。輸入一個非整型的值將導(dǎo)致一個類型錯誤,輸入一個不在1-10范圍內(nèi)的值,返回一個null數(shù)組。如果我們輸入一個正確的參數(shù),我們將被展示如下的XML文件:
It's that easy.
就這么簡單。
Caching WebServices
Often a WebService will return the same results over multiple calls, so it makes sense to cache the information to speed things up a little. Doing so in ASP.NET is as simple as adding a CacheDuration attribute to your WebMethod:
WebService常常在多個調(diào)用上返回相同的值,所以就自然想到緩存信息進行加速。在ASP.NET做這件事,只要簡單地為你的WebMethod增加一個CacheDuration 屬性:
public?ClientData[]?GetClientData(int?Number)
{
The CacheDuration attribute specifies the length of time in seconds that the method should cache the results. Within that time all responses from the WebMethod will be the same.
CacheDuration屬性指定方法應(yīng)該緩存返回值的時間長度,以秒計算。在這段時間里所有從WebMethod的responses將是相同的。
You can also specify the CacheDuration using a constant member variable in your class:
你還可以通過在你的類中使用一個常量成員指定CacheDuration :
[WebMethod(CacheDuration?=?CacheTime)]
public?ClientData[]?GetClientData(int?Number)
{
Adding Descriptions to your WebMethods
In the default list of WebMethods created when you browse to the .asmx file it's nice to have a description of each method posted. The Description attribute accomplishes this.
你瀏覽.asmx文件時,在WebMethods的默認列表,最好能對每一個方法有一個描述。Description 屬性能夠完成這個。
[WebMethod(CacheDuration?=?30,
?Description="Returns?an?array?of?Clients.")]
public?ClientData[]?GetClientData(int?Number)
{
Your default .asmx page will then look like the following:
你的默認.asmx頁面就像下面這樣:
There are other WebMethod attributes to control buffering, session state and transaction support.
還有其他WebMethod屬性控制緩沖,session狀態(tài)和事務(wù)支持。
Deploying the WebService
Now that we have a WebService it would be kind of nice to allow others to use it (call me crazy, but...). Publishing your WebService on your server requires that your solution be deployed correctly. On the Build menu of Visual Studio is a "Deploy" option that, when first selected, starts a Wizard that allows you to add a Deployment project to your solution. This creates an installation package that you can run on your server which will create the necessary directories, set the correct parameters and copy over the necessary files.
現(xiàn)在我們有了一個WebService,能很好地讓其他人使用(瘋狂地調(diào)用我吧,但…).在你的服務(wù)器發(fā)布你的WebService需要你的solution正確地部署。在Visual Studio的”Deploy”菜單,有一個” Deploy”選項,當?shù)谝淮芜x擇的時候,開始一個向?qū)г试S你增加一個部署工程到你的solution。這就創(chuàng)建一個你可以在你的服務(wù)器上運行的安裝包,將會創(chuàng)建需要的目錄,設(shè)置爭取的參數(shù),覆蓋必要的文件。(應(yīng)該又是版本問題,并不能找到作者所說的菜單,你可以在文件-新建-項目里找到安裝和部署項目)
This doesn't really give you an idea of what, exactly, is happening, so we'll deploy our MyService manually.
這實際上并沒有給你什么想法,其實,就那么發(fā)生了,所以我們手動部署了我們的MyService。
Deploying the application is done using the steps in Getting the demo application to run. We need to create a directory for our service (or use an existing directory) for our .asmx file, and we need to have the service's assembly in the application's bin/ directory. Either place the .asmx file in a subdirectory on your website and place the assembly in the /bin folder in your website's root, or place the /bin in the subdirectory containing the .asmx file and mark that directory as an application (see above).
部署程序使用了Getting the demo application to run里的步驟。我們需要為我們的service為我們的.asmx文件的創(chuàng)建一個目錄(或者已經(jīng)存在一個目錄),我們需要把我們的service的程序集放在程序的bin/文件夾?;蛘甙?/span>.asmx文件放在我們的網(wǎng)站的一個子文件夾里,把程序集放在你的網(wǎng)站的根目錄的/bin文件夾或者把/bin放在存在.asmx文件的文件夾的子文件夾中,把那個文件夾作為程序(看前面)
If you choose to create a separate directory and mark it as an application then Within this directory you need to add the following files and directories:
如果你選擇創(chuàng)建一個分離的文件夾,把它作為程序,那么你就需要把以下文件和目錄放在里面:
| MyService.asmx | This file acts as the URL for your service |
| MyService.disco | The discovery document for your service |
| web.config | Configuration file for your service that overrides default web settings (optional). |
| /bin | This directory holds the assembly for your service |
| /bin/MyService.dll | The actual service asembly. |
?
(譯注:反正到最后我都沒有部署成功,還請大家指教)
Conclusion
Writing WebServices is extremely easy. Using the Visual Studio. NET wizards makes writing and deploying these services a point and click affair, but even if you wish to do it by hand then the steps involved are extremely simple.
寫WebService是十分容易的。使用Visual Stdio.NET向?qū)沟脮鴮懞筒渴疬@些services就是一個點擊那回事,但是你想要自己手寫,那么相關(guān)的步驟也是很簡單的。
總結(jié)
以上是生活随笔為你收集整理的Code Project - Your First C# Web Service的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OJ1068: 二进制数(C语言)
- 下一篇: 内核错误Linux,ubuntu14.0