您的位置:首页 > 编程语言 > C#

C#实现和调用WebService

2018-03-29 13:45 309 查看
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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: