当前位置:首页 > Windows程序 > 正文

C# webservice初探

2021-05-26 Windows程序

由于工作的终端以前是直接对数据库进行操作,导致每次终端会卡死,严重影响业务进度。所以进行了技术调整,用webservice来作为数据对接的一个中间件,自己也部署了一下webservice环境和入门。总体来说分为以下这几个步骤:

1.部署IIS环境

2.创建webservice

3.编写测试程序引用webservice

我们就开始一步一步来进行。   首先部署IIS环境,win7中打开控制面板--->程序--->打开或关闭Window功能

技术分享


选中里面的选项

技术分享

这样IIS环境就配置好了,我们可以在开始编写webservice程序,在visual studio2008中建立一个“ASP.NET服务应用程序”,名字叫MathService

技术分享


打开MathService.asmx文件,编写如下代码:

using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Linq; namespace MathService { /// <summary> /// Service1 的摘要说明 /// </summary> [WebService(Namespace = "")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 // [System.Web.Script.Services.ScriptService] public class Service1 : System.Web.Services.WebService { [WebMethod] public int Add(int a,int b) { return a + b; } [WebMethod] public int Sub(int a, int b) { return (a - b); } [WebMethod] public int Mul(int a, int b) { return a * b; } [WebMethod] public int Div(int a, int b) { return a / b; } } }         在“解决方案资源管理器”中,选中项目,点击右键,选择“生成”,然后发布,(如果是部署到本地的话就是本地的一个目录,我的是D:\net\webservice\).

然后回到IIS信息服务管理器中,在Default Web Site下面新建一个“虚拟目录”,按照如下的方式进行设置:

技术分享

  

技术分享


然后我们回到visual studio2008,重新建立一个控制台应用程序来测试webservice所提供的方法是否我们可以引用。当然建立以后,,我们还需要添加web reference,如图:

技术分享


选中项目,点击鼠标右键,选中“添加web引用”,点击高级引用属性,我们可以出现我们在IIS中配置好的webservice项目。

技术分享


由于我是在本地电脑进行测试,调试用的,所以我选择 “本地计算机的Web服务”,他就会出现我们在IIS中配置好的webservice。

技术分享



把URL复制上去,点击”前往就可以了“。然后下面是测试webservice连接程序的代码,调用了自己编写的webservice中的Add方法

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ForkWebService { class Program { static void Main(string[] args) { localhost.Service1 myMathService = new localhost.Service1(); Console.Write("2+4={0}", myMathService.Add(2, 4)); Console.ReadLine(); } } }


         运行程序,我们就可以在控制台看到结果:

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/71333.html