C#的WebService完全教程(之三)(c# web服务)

上一讲说过,WebService是一个程序,现在就说怎么写这个程序的问题。

用的语言是C#,用的工具是VisualStudio。


创建项目


文件 > 新建 > 项目

Visual C# > Web > ASP.NET空Web应用程序



刚创建时,“解决方案资源管理器”中的目录:



右键点项目名称(在这里是“WebApplication1”),在弹出菜单中选择“添加 > 新建项”,在弹出的窗口中选择“Visual C# > Web > Web服务”:


这将创建后缀为“.asmx”的文件,出现在目录中:



简单的编辑


在下面这个简单范例中,WebService1.asmx调用一个叫“HelloWorld”的C#方法,该方法将在调试或发布时被封装在dll文件中。

在WebService1.asmx中,Visual Studio先替我们写了代码模版,如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services; 

namespace WebApplication1 //这是项目的命名空间名称,只需要在本机有唯一性

{

    ///这是Web服务的命名空间名称,要求在整个互联网上有唯一性

    [WebService(Namespace = "http://tempuri.org/")] //发布前,必须改成不会与别人重复的命名空间名称,通常用网站域名,因为这是肯定不会重复的,注意,后面必须有斜杠

    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    [System.ComponentModel.ToolboxItem(false)]

    public class WebService1 : System.Web.Services.WebService

    {

        [WebMethod]

        public string HelloWorld() //这里将要改成自己的方法

        {

            return "Hello World";

        } 

        //也可以用类似上面那一段的格式,添加方法

        //即使方法有返回值,标头仍然是[WebMethod]

    }

}

把它改成这样:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services; 

namespace WebApplication1

{

    [WebService(Namespace = "http://www.myweb.com/")] //在这里,修改了Web服务命名空间名称

    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    [System.ComponentModel.ToolboxItem(false)]

    public class WebService1 : System.Web.Services.WebService

    {

        [WebMethod]

        public string addStr() //在这里,修改了函数名和函数内容

        {

            return x + y;

        }

    }

}

还要修改Web.config,加上远程访问的代码(下面从<webServices>到</webServices>的部分),不然以后传到服务器上,别人无法通过互联网访问这个WebService。

<?xml version="1.0"?>

<!--

  有关如何配置 ASP.NET 应用程序的详细信息,请访问

  http://go.microsoft.com/fwlink/?LinkId=169433

 -->

<configuration>

  <system.web>

    <compilation debug="true"/>

    <httpRuntime/> 

    <webServices>

      <protocols>

        <add name="HttpSoap"/>

        <add name="HttpPost"/>

        <add name="HttpGet"/>

        <add name="Documentation"/>

      </protocols>

    </webServices>  

  </system.web>

</configuration>


调试


与通常的Visual Studio调试一样,按F5键即可。

然后出现的是网页浏览器,如果出现“HTTP错误403.14……服务器被配置为不列出此目录的内容”,那多半是因为源码中“[WebService(Namespace = "http://tempuri.org/")]”中的“http://tempuri.org/”并不是互联网上唯一的,将它改成唯一的(哪怕是不存在的)域名即可,但注意,一定要以“/”结尾。

在正常情况下,此网页浏览器会打开我们刚才设的首页WebService1.asmx,并以一个链接显示此页中的方法“addStr”:


单击“addStr”会打开这个页面:


在这里输入x、y的值后点“调用”,会打开显示结果的页面:


回到Visual Studio中,“调试 > 停止调试”。

好了,程序写完了。下一讲说说怎么向服务器上传的问题。