C#实现和调用WebService

本文介绍了使用C#调用WebService的方法,包括高级封装和原生方式,并提供了具体示例代码,展示了如何调用获取天气信息及计算求和的WebService。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Webservice本本身是使用的soap+WSDL+UDDI三者的组合, soap用来描述传递信息的格式, WSDL 用来描述如何访问具体的接口, uddi用来管理,分发,查询webService。 但是C#在这个基础上又做了进一步的封装,所以使用C#语言的时候又两种方法可以调用WebService,即高级封装的和原生的(即http对象的方式)。

WebService是RPC(远程过程调用),说白了,就是在一台计算机上调用另一台计算机上的函数(而不是只用来请求另一台计算机上的数据,数据的请求又很多方法,socket, 消息队列等等,),WebSocket的服务端一般是Web服务,C/S和B/S架构均可以调用这个B/S架构上的WebService。

第一种

下面代码是调用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string city = "北京";
            WebApplication.cn.com.webxml.www.WeatherWebService ws = new WebApplication.cn.com.webxml.www.WeatherWebService();
            string[] r = ws.getWeatherbyCityName(city);
            string str = null;
            if (r == null)
            {
                str = "无" + city + "城市的天气信息";

            }
            foreach(string line in r)
            {
                Console.WriteLine(line);
            }

            Console.WriteLine("----------------------------------------------------");
            WebApplication.localhost.WebService aa = new WebApplication.localhost.WebService();
            int c = aa.getSum(1, 3);
            Console.WriteLine(c);

            Console.ReadKey();

        }
    }
}

下面代码是定义webservice

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

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

    public WebService()
    {

        //如果使用设计的组件,请取消注释以下行 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }
    [WebMethod]
    public int getSum(int a ,int b)
    {
        return a + b;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值