C#调用WebService接口和创建WebService接口

调用WebService接口

对于初学者来说,在vs2012环境中,大家有可能不知道Web References文件夹是如何来的,它是通过右击项目,选择其中的”添加服务引用“,如图所示:

之后,得到”添加服务引用“的页面,我也把图截了下来,如图:

再选择”高级“按钮,进入下图

  根据上图的指示,在URL这栏输入互联网上公开的WebServices(http://www.webxml.com.cn/WebServices/WeatherWebService.asmx)来实现天气预报。这样就可以通过代码来获取用户输入城市的天气了。实现的效果图如下:

  通过点击按钮,系统会输出用户所填城市的天气信息。后台代码如下:

protected void Button2_Click(object sender, EventArgs e)
{
            WebApplication1.cn.com.webxml.www.WeatherWebService ws = new WebApplication1.cn.com.webxml.www.WeatherWebService();
            string[] r = ws.getWeatherbyCityName(this.TextBox4.Text);
            this.TextBox3.Text = "";
            if (r == null)
            {
                this.TextBox3.Text = "无" + this.TextBox4.Text + "城市的天气信息";
                return;
            }
            foreach (string i in r)
            {
                this.TextBox3.Text += i;
            }
}

 

创建WebService接口

我们选中一个项目,右击新建一个“Web服务”,如下图所示:

完成创建以后,就会在项目文件中出现“Service.asmx”文件,我们在Service.asmx.cx中添加一个简单的求和方法,代码如下:

namespace Web_Service
{
    /// <summary>
    /// WebService1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod]
        public int GetSum(int a,int b)
        {
            return a+b;
        }

    }
}

那么,我们怎么在其它项目中调用这个方法呢,其实这和刚才我们所说的,调用天气的webservice是一个道理,首先,通过添加“web服务引用”将,你写的webservice引用进来,我们需要注意的是其中有一处要我们填写请求webservice的URL地址,我们该怎么写?其实呢,也很简单,就是,你将Service.asms在浏览器中浏览的地址,如我的是:http://localhost:12197/Service.asmx。

  引用完成后,我们通过代码来实现它,首先还是来看下运行后的效果图:

 

  最后,再贴上代码:

protected void Button1_Click(object sender, EventArgs e)
{
            WebApplication1.localhost.WebService1 aa = new WebApplication1.localhost.WebService1();
            this.Label1.Text = aa.GetSum(Convert.ToInt32(this.TextBox1.Text), Convert.ToInt32(this.TextBox2.Text)).ToString();
}

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值