winfrom静态调用WebService

来源:互联网 发布:网络词cgm什么意思 编辑:程序博客网 时间:2024/06/03 20:50

1.首先打开我们的vs,文字太啰嗦,下面以图片方式展示:创建的webservice,就是从这里调用我们需要的方法。


2.创建好后,我们打开Service.cs文件,里面有一个默认的方法,之后我们可以自己添加几个,下面是我添加的2个。代码中描述的很清楚了。

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Services;[WebService(Namespace = "http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 // [System.Web.Script.Services.ScriptService]public class Service : System.Web.Services.WebService{    public Service () {        //如果使用设计的组件,请取消注释以下行         //InitializeComponent();     }    [WebMethod]    public string HelloWorld() {        return "Hello World";    }    [WebMethod (Description="返回字符串")]    public string GetString(string str)    {        return str;    }    [WebMethod(Description = "返回两数之和")]    public double GetSum(double a, double b)    {        return (a + b);    }}


这样一个WebServide算是创建完了,下面就是我们从winform中调用他的方法了。(调用之前一定要先运行此WebService,否则会报错:无法连接到远程服务器。)

为了避免忘记,我们先运行起来。(复制一下那个 地址,下面将会用到。)


3.我们创建一个winform窗体,在此不赘述。创建好后,右击你的项目,“添加服务引用”,弹出下面窗体,步骤已指明。


点击“高级”后,在弹出的窗体,点击--“添加web应用”,弹出下面窗体,最后“添加引用”就算是添加上了:


下面就是代码中实例化这个服务了,当做类来对待了:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace T5_WebService
{
    public partial class Form1 : Form
    {
        localhost.Service local_S = new localhost.Service();

        public Form1()
        {
            InitializeComponent();
        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            double number_01 = Convert.ToDouble(txtb_01.Text.ToString().Trim());
            double number_02 = Convert.ToDouble(txtb_02.Text.ToString().Trim());
            txtb_03.Text = local_S.GetSum(number_01, number_02).ToString();
        }
    }
}

4.运行我们的winform窗体,看看结果:




本人新手,有什么遗漏的或者不对的,大家指正啊,不会的也可以贴上来,大家一起解决。


0 0
原创粉丝点击