• Web Service 入门例子


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

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

    然后在项目中添加Web 服务

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

     1 [WebMethod(Description = "求和")]
     2     public double Add(double i, double j)
     3     {
     4         return i + j;
     5     }
     6 
     7     [WebMethod(Description = "求差")]
     8     public double Sub(double i, double j)
     9     {
    10         return i - j;
    11     }
    12     [WebMethod(Description = "求积")]
    13     public double Multi(double i, double j)
    14     {
    15         return i * j;
    16     }
    17     [WebMethod(Description = "求商")]
    18     public double Division(double i, double j)
    19     {
    20         if (j != 0)
    21             return i / j;
    22         else
    23             return 0;
    24     }

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

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

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

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

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

     1    WindowsFormsApplication1.ServiceReference1.WebServiceSoapClient wsc = new ServiceReference1.WebServiceSoapClient();
     2         /// <summary>
     3         /// 求和
     4         /// </summary>
     5         private void btnAdd_Click(object sender, EventArgs e)
     6         {
     7             txtResult.Text = wsc.Add(Convert.ToDouble(txtNumber1.Text),Convert.ToDouble(txtNumber2.Text)).ToString();
     8         }
     9 
    10 
    11         /// <summary>
    12         /// 求差
    13         /// </summary>
    14         private void btnSub_Click(object sender, EventArgs e)
    15         {
    16             txtResult.Text = wsc.Sub(Convert.ToDouble(txtNumber1.Text), Convert.ToDouble(txtNumber2.Text)).ToString();
    17         }
    18 
    19         /// <summary>
    20         /// 求积
    21         /// </summary>
    22         private void btnMulti_Click(object sender, EventArgs e)
    23         {
    24             txtResult.Text = wsc.Multi(Convert.ToDouble(txtNumber1.Text), Convert.ToDouble(txtNumber2.Text)).ToString();
    25         }
    26 
    27         /// <summary>
    28         /// 求商
    29         /// </summary>
    30         private void btnDiv_Click(object sender, EventArgs e)
    31         {
    32             txtResult.Text = wsc.Division(Convert.ToDouble(txtNumber1.Text), Convert.ToDouble(txtNumber2.Text)).ToString();
    33         }

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

  • 相关阅读:
    两个栈实现一个队列,C语言实现,队列可伸缩,容纳任意数目的元素。
    创建双向链表的一个陷阱!!
    实现单链表的倒置
    《征服c指针》学习笔记-----统计文本单词数目的程序word_count
    [stm32]IAR环境 hardfault定位
    [FreeRTOS] 函数笔记
    [C语言]字符串函数大全
    [verilog]常用任务之模拟UART Rxd引脚输入数据
    [git] 知识点
    [FreeRTOS] 临界区处理
  • 原文地址:https://www.cnblogs.com/mengyirensheng/p/3255639.html
Copyright © 2020-2023  润新知