Code Project - Your First C# Web Service

来源:互联网 发布:静态nat加端口号配置 编辑:程序博客网 时间:2024/04/28 16:56

原文连接: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;
    }

原创粉丝点击