Code Project - Your First C# Web Service

原文連接:http://www.codeproject.com/cs/webservices/myservice.asp
作者:Chris Maunder

Introduction

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.

創建你的第一個web service是難以置信地容易。事實上,通過使用Visual Studio.NET的嚮導,你可以無需編碼在幾分鐘內創建和運行你的第一個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.

比如說,我已經創建了一個叫做MyService service在我本地機器的/WebServices 目錄。文件將被創建在/WebServices/MyService 目錄。

Create.gif

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存取的方法。

result2.gif

 
[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:

如果我們編譯,然後導航到擴展名爲.asmx的頁面,就展示給我們一個form允許我們輸入一個值作爲參數。輸入一個非整型的值將導致一個類型錯誤,輸入一個不在1-10範圍內的值,返回一個null數組。如果我們輸入一個正確的參數,我們將被展示如下的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常常在多個調用上返回相同的值,所以就自然想到緩存信息進行加速。在ASP.NET做這件事,只要簡單地爲你的WebMethod增加一個CacheDuration 屬性:

 

[WebMethod(CacheDuration = 30)]
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屬性指定方法應該緩存返回值的時間長度,以秒計算。在這段時間裏所有從WebMethodresponses將是相同的。

You can also specify the CacheDuration using a constant member variable in your class:

你還可以通過在你的類中使用一個常量成員指定CacheDuration

private const int CacheTime = 30;    // seconds

[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頁面就像下面這樣:
descriptions.gif

There are other WebMethod attributes to control buffering, session state and transaction support.

還有其他WebMethod屬性控制緩衝,session狀態和事務支持。

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.

現在我們有了一個WebService,能很好地讓其他人使用(瘋狂地調用我吧,但.在你的服務器發佈你的WebService需要你的solution正確地部署。在Visual Studio”Deploy”菜單,有一個 Deploy”選項,當第一次選擇的時候,開始一個嚮導允許你增加一個部署工程到你的solution。這就創建一個你可以在你的服務器上運行的安裝包,將會創建需要的目錄,設置爭取的參數,覆蓋必要的文件。(應該又是版本問題,並不能找到作者所說的菜單,你可以在文件-新建-項目裏找到安裝和部署項目)


This doesn't really give you an idea of what, exactly, is happening, so we'll deploy our
MyService manually.


這實際上並沒有給你什麼想法,其實,就那麼發生了,所以我們手動部署了我們的
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文件的創建一個目錄(或者已經存在一個目錄),我們需要把我們的service的程序集放在程序的bin/文件夾。或者把.asmx文件放在我們的網站的一個子文件夾裏,把程序集放在你的網站的根目錄的/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:


如果你選擇創建一個分離的文件夾,把它作爲程序,那麼你就需要把以下文件和目錄放在裏面:


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嚮導使得書寫和部署這些services就是一個點擊那回事,但是你想要自己手寫,那麼相關的步驟也是很簡單的。

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。默認情況下,一下類將被創建:

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)

繼承自HttpApplicationASP.NET裏的這個文件相當於一個標準ASP global.asa文件

WebService1 (in WebService1.cs)

繼承自System.Web.Services.WebService.

這是你的WebService類,它允許你展示那些能被叫做WebServices的方法

There are also a number of files created:

還有另外一些文件被創建:

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

包含你的程序集的版本和設置信息

web.config

定義你的程序如何運行(調試選項,cookies的使用等等)

MyService.disco

爲你的服務發現信息(譯註:我自己新創建的沒發現這個文件,也許版本不一樣,我的是VS.NET2003

WebService1.asmx

你的WebService URL。在瀏覽器導航到這個文件,你將得到一個用戶友好的頁面,展示了可用的方法,需要的參數和返回值。甚至提供了供你在頁面上測試服務的Forms

bin/MyService.dll

事實上的WebService組件。這是在你建立service的時候創建的。

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創建的類(在我們現在的情況下)叫做WebService1,它是在MyService 命名空間下的。部分代碼如下所示:

 

namespace 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)。

嘿嘿,你已經建立運行了一個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應該跟一個命名空間相聯繫。你用嚮導獲得的service會有一個叫做http://tempuri.org的命名空間。如果你照現在的樣子編譯運行,你將得到一個很長的相關信息指出你應該選擇一個新的命名空間,所以我們就增加一個命名空間,那麼WebService的描述就像下面這樣:

 

[WebService(Namespace="http://codeproject.com/webservices/",
            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,

想測試服務你只要右鍵點擊資源管理器裏的WebService1.asmx ,然後選擇“在瀏覽器中查看”。測試頁面如下所示

test.gif


When invoked this returns the following:

點擊調用按鈕返回一下信息:

result.gif

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:

如果你下載了這篇文章的源代碼,那你需要在你的網站的根目錄創建一個'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.

導航到http://localhost/WebServices/WebService1.asmx並不能向你展示WebService,因爲你需要保證webservice的程序集在程序的/bin文件夾。你還將大縣你不能載入solution file Myservice.sln。爲了一石二鳥,你需要點燃IIS management console(中文版裏就是Internet信息服務),打開你的網站節點,右擊WebServices文件夾,點擊屬性。點擊創建按鈕創建一個新的程序,點確定。/WebServices 文件夾現在是一個程序,那麼.NET framework將從/WebServices/bin 文件夾載入WebService程序集,你將能載入和建立MyService.sln solution。(譯註:其實執行作者所說的操作以後還是不行,是不是版本不匹配?要想使用下載的代碼,你只要自己建一個WebService,然後把源文件裏的“WebService1.cs”文件裏的相關代碼拷貝到你那就行了,然後就可以運行了)

create_app.gif

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.

現在我們有了一個WebService。沒什麼特別值得激動的,但我們到現在還沒做什麼額外的工作(這句話建議還是看原文-_-!!)爲了讓這東西稍爲有趣一點,我們將定義一個一個方法,返回一個自定義結構的數組。

Within the MyService namespace we'll define a structure called ClientData:

MyService命名空間裏,我們將定義一個叫做ClientData的結構:

 

    public struct ClientData
    
{
        
public String Name;
        
public int    ID;
    }

發佈了42 篇原創文章 · 獲贊 3 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章