wcf简单的创建和运用

创建一个控制台应用程序,命名为wcftest,并在同一解决方案中添加一个wcf服务应用程序

在wcf项目中会自动生成Service1.svc服务程序文件和IService1.cs契约接口

IService1.cs

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

namespace WcfService1
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”。
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);
        // TODO: 在此添加您的服务操作
    }

}

服务类必须要添加[ServiceContract]特性,方法要添加[OperationContract]特性,这样才能被客户端调用,wcf服务需要这几个特性来制定服务契约,规定wcf消息交换模式和消息的格式等

Service1.svc

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

namespace WcfService1
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“Service1”。
    // 注意: 为了启动 WCF 测试客户端以测试此服务,请在解决方案资源管理器中选择 Service1.svc 或 Service1.svc.cs,然后开始调试。
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }
    }
}

测试用,所以我只保留了GetData方法

现在服务和项目在同一解决方案中,可以直接引用服务,添加服务引用,点击发现,就能看到创建的wcf

添加服务(服务修改后要重新生成一下,不然可能会报错)

调用服务

客户端wcftest中的程序

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

namespace wcftest
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
            Console.WriteLine(client.GetData(1));
            Console.ReadKey();
        }
    }
}

程序输出结果

结果出来了,证明wcf是可以用的,现在把wcf部署到iis上

打开iis,创建一个应用程序池,取名wcfpool

然后添加一个空网站,程序池选择刚刚建立的wcfpool,用户名为wcfservice,物理地址指向一个空文件夹

因为在本机上,所以主机位localhost,也可以填上本机的ip地址

在随便找个路径创建一个WcfTest的文件夹,在文件夹中放入刚才创建的wcf应用程序的Service1.svc服务程序文件和IService1.cs契约文件还有web.config配置文件

在WcfTest中再创建一个bin文件夹,放入刚才创建的wcf应用程序的bin目录下的WcfService1.dll文件

在iis中的wcfservice网站上创建一个应用,名称为wcftest,物理路径为刚创建的WcfTest文件夹

然后可以在iis中看到生成了相应的应用程序,右键浏览Service1.svc

如果在浏览器中出现如下结果

说明wcf已经成功部署到iis了,再看一下浏览器的地址栏,是不是跟我们配置的网站的路径一样,主机localhost 应用wcftet下的Service1.svc

如果主机名输入域名,再输入本机ip,则可以通过域名www.xxxx.com的方式访问

在内网的话也可以用本机的内网ip ,地址将会是http://xxx.xxx.xxx.xxx/wcftest/Service1.svc

现在算是把wcf部署到服务器端了,然后就是创建一个客户端访问试一下,同样创建一个控制台程序,然后添加服务引用,地址填上刚才的浏览器地址

能找到wcf,然后再试用一下,依然可以成功调用

总结:初步了解wcf,依然有很多不明白的,比如说wcf的契约,绑定,消息,安全,元数据等

  

原文地址:https://www.cnblogs.com/fuhai/p/5220045.html