关于WCF一些基础。

关于WCF

Windows Communication Foundation(WCF)是由微软发展的一组数据通信的应用程序开发接口,可以翻译为Windows通讯接口,它是.NET框架的一部分。由 .NET Framework 3.0 开始引入。

WCF的最终目标是通过进程或不同的系统、通过本地网络或是通过Internet收发客户和服务之间的消息。

WCF合并了Web服务、.net Remoting、消息队列和Enterprise Services的功能并集成在Visual Studio中。

WCF专门用于面向服务开发。

使用

目录结构如下:


1 新建空白解决方案wcfapplication。

2 新建WCF服务应用程序testwcfService。

3 添加-新建项-WCF服务 User.svc

IUser.cs 代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace testwcfService
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IUser”。
    [ServiceContract]//来说明接口是一个WCF的接口,如果不加的话,将不能被外部调用。
    public interface IUser
    {
        [OperationContract]//来说明该方法是一个WCF接口的方法,不加的话同上。
        string ShowName(string name);
    }
}
View Code

其中[ServiceContract]用来说明接口是一个WCF的接口,如果不加的话,将不能被外部调用。

[OperationContract]用来说明该方法是一个WCF接口的方法,不加的话同上。

User.svc代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace testwcfService
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“User”。
    public class User : IUser
    {
        public string ShowName(string name)
        {
            string wcfName = string.Format("WCF服务测试,名字:{0}",name);
            return wcfName;
        }
    }
}
View Code

则第一个WCF方法创建成功。

设User.svc为起始页,F5运行。

界面如下:

发布:

发布与部署同网站

部署成功后浏览到的界面如下:

上图中的http://localhost:55551/User.svc?wsdl即为我们要引用的服务地址。

为了方便这里就不新建一个新的网站了。直接在wcf项目中建立一个web网页,WCFClient.aspx

引用-右键-添加服务引用-在地址中输入http://localhost:55551/User.svc?wsdl

单击确定,则引用成功。

WCFClient.aspx页面中拖入一个文本框控件和 一个按钮。

WCFClient.aspx.cs页面代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using testwcfService.ServiceReference;

namespace testwcfService
{
    public partial class WCFClient : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            UserClient user = new UserClient();
            string result = user.ShowName(this.TextBox1.Text);
            Response.Write(result);
            user.Close();
        }
    }
}
View Code

运行程序:页面如下:

 

参考资料:

http://www.cnblogs.com/iamlilinfeng/archive/2012/09/25/2700049.html

WCF应用的通信工程:http://www.cnblogs.com/iamlilinfeng/archive/2012/09/26/2703759.html

WCF与实体类:http://www.cnblogs.com/hexinxiaoyao/archive/2013/04/09/3010155.html

posted @ 2014-03-24 13:55  时光未曾老去.  阅读(198)  评论(0编辑  收藏  举报