Web Service 入门例子

在网上很常见的一个列子,实现计算器,看完总得自己练练,不然一段时间不接触又忘了

新建一个空网页,因为.net framework 4.0 不能直接建web 服务,只能在项目中添加

Web Service 入门例子

然后在项目中添加Web 服务

Web Service 入门例子

在WebService.cs中写要调用的方法

 [WebMethod(Description = "求和")]
public double Add(double i, double j)
{
return i + j;
} [WebMethod(Description = "求差")]
public double Sub(double i, double j)
{
return i - j;
}
[WebMethod(Description = "求积")]
public double Multi(double i, double j)
{
return i * j;
}
[WebMethod(Description = "求商")]
public double Division(double i, double j)
{
if (j != )
return i / j;
else
return ;
}

新建一个WINDOWS 窗体程序作为客户端

Web Service 入门例子

在浏览器中查看,查看之前的web service地址

Web Service 入门例子

Web Service 入门例子

把地址复制下来后在WINDOWS 窗体程序总添加服务引用

Web Service 入门例子

输入之前的web service地址,前往,然后确定

Web Service 入门例子

编码按钮事件,调用web service中的方法

    WindowsFormsApplication1.ServiceReference1.WebServiceSoapClient wsc = new ServiceReference1.WebServiceSoapClient();
/// <summary>
/// 求和
/// </summary>
private void btnAdd_Click(object sender, EventArgs e)
{
txtResult.Text = wsc.Add(Convert.ToDouble(txtNumber1.Text),Convert.ToDouble(txtNumber2.Text)).ToString();
} /// <summary>
/// 求差
/// </summary>
private void btnSub_Click(object sender, EventArgs e)
{
txtResult.Text = wsc.Sub(Convert.ToDouble(txtNumber1.Text), Convert.ToDouble(txtNumber2.Text)).ToString();
} /// <summary>
/// 求积
/// </summary>
private void btnMulti_Click(object sender, EventArgs e)
{
txtResult.Text = wsc.Multi(Convert.ToDouble(txtNumber1.Text), Convert.ToDouble(txtNumber2.Text)).ToString();
} /// <summary>
/// 求商
/// </summary>
private void btnDiv_Click(object sender, EventArgs e)
{
txtResult.Text = wsc.Division(Convert.ToDouble(txtNumber1.Text), Convert.ToDouble(txtNumber2.Text)).ToString();
}

整个计算并不是在本地进行的,是在Web服务端进行计算的然后将结果通过XML返还给了调用方的,所以,在运行该程序的时候,WebService程序还必须启动,否则会报无法连接远程服务器的异常

上一篇:【初级】linux cp 命令详解及使用方法实战


下一篇:cp命令覆盖文件时不用按Y来确认的方法