WCF是什么?
Windows CommunicationFoundation,Windows通信基础框架,它整合了早期.Net版本中的Remoting(远程技术)、Socket(通信技术)、基于HTTP协议的Web Serviece等多种通信技术。
对比Web Service 和WCF:
WCF包含了Web Service相关的内容,以SOAP消息作为数据传输载体,而且WCF可以进行复杂数据对象的传递、服务回调。
除了HTTP方式通信外,WCF也可以使用TCP、UDP等协议。
既可以寄宿在IIS服务上,还可以在Console应用程序进程中运行。
我们使用的VS2017
参考以下步骤,建立一个Web Service
【Web Service服务端】
首先,建立一个WebApplication(空Web应用程序) ,然后在应用程序里添加一个web服务(WebService.asmx)
/// <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(string name)
{
return name+ "Hello World";
}
}
其次:我们在IIS上发布我们的Web服务
在Web应用程序右击鼠标,点击发布——成功后打开控制面板——管理工具——IIS管理器——在网站下添加网站
之后浏览网站:——Web Service发布成功,服务端创建完成
【客户端】
创建客户端:引用Web服务,把name值传递过去
首先:再新建立一个WebApplication(空Web应用程序)——添加WebService引用(添加服务——高级——添加Web引用)
其次:添加Web窗体(Hello)—-窗体上添加text和button
protected void Button1_Click(object sender, EventArgs e)
{
WebReference.WebService1 hello = new WebReference.WebService1();
this.TextBox1.Text = hello.HelloWorld("Web");
}
参考下列步骤,建立WCF
首先,建立一个WebApplication(空Web应用程序) ,然后在应用程序里添加一个wcf服务:
会出现一个app.config配置文件;IService1接口类;Service1jich继承接口的类
IService1
[ServiceContract]//服务契约
public interface IService1
{
[OperationContract]//服务契约
string DoWork(string name );
}
Service1
public class Service1 : IService1
{
public string DoWork(string name)
{
return name + "hello world";
}
}
app.config
到此服务端完成,上面提到WCF的宿主可以是IIS,也可以是应用程序,这里就用应用程序kong控制体Console作为宿主。
在Program,连接WCF服务:
class Program
{
static void Main(string[] args)
{
//连接WCF服务,实例化服务地址
ServiceHost host = new ServiceHost(typeof(Service1));
//打开服务
host.Open();
Console.WriteLine("服务启动成功");
Console.Read();
}
}
之后,我们可以看到生成的exe文件:wcf服务已经启动
接着,创建客户端:Client
首先:再新建立一个Client(空Web应用程序)——添加服务引用(鼠标右击——添加服务引用)
注意:要在WCF服务的exe文件启动的状态下添加
使用引用的wcf服务,传值过去
class Program
{
static void Main(string[] args)
{
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
Console.WriteLine(client.DoWork("白脱皮"));
Console.ReadKey();
}
}
截止到这里,客户端实现了传一个string“白脱皮”到WCF服务端的name+HelloWorld
最后显示结果:白脱皮HelloWorld(如果出现错误:VS用管理员身份运行)
截止到这里web服务和WCF服务的例子完成
他们的创建和引用方式都很相似,但是在实现功能上还是有很大的差别。WCF服务是一个更加全面的通信服务。