建立第一个wcf程序

使用管理员权限启动vs (否者将导致ServiceHost开启失败 权限不足)

1.创建一个空的控制台程序

2.添加程序集引用 System.ServiceModel

3.写入一些代码 如下

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

namespace HelloWCF
{
    [ServiceContract]
    interface IHelloWCF
    {
        [OperationContract]
        string HelloWCF();
    }
    public class HelloWCF : IHelloWCF
    {
        string IHelloWCF.HelloWCF()
        {
            return "HelloWCF";
        }
    }
}

  这样便创建了一个wcf的服务接口

接下来需要绑定一个host并开启服务

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

namespace HelloWCF
{
    class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://192.168.5.14/MyService");
            ServiceHost host = new ServiceHost(typeof(HelloWCF), baseAddress);
            host.AddServiceEndpoint(typeof(IHelloWCF), new WSHttpBinding(), "HelloWCF");
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            host.Description.Behaviors.Add(smb);
            host.Open();
            Console.WriteLine("已开启");

            Console.ReadLine();
            host.Close();
            Console.WriteLine("已关闭");
            Console.ReadLine();


        }

    }
}

  

  Uri baseAddress = new Uri("http://192.168.5.14/MyService");  创建一个url对象用于绑定寄托的host地址

ServiceMetadataBehavior smb = new ServiceMetadataBehavior();   创建一个服务元数据行为对象 然后把它加入到宿主ServiceHost 对象的行为集合中去,这样元数据交换就被打开了
 smb.HttpGetEnabled = true;   设置服务允许使用get请求

这样服务端便绑定完成

启动控制台程序 另外打开一个vs编辑器 创建一个空的控制台程序 下面将演示客户端调用服务过程

为项目添加服务引用

添加引用

添加后会生成一个服务文件 里面有一些class class中包含我们的服务 调用方式即调用函数 接收出参

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

namespace HelloWCFClient
{
    class Program
    {
        static void Main(string[] args)
        {
            var client= new HelloWCFClient.HelloWCF.HelloWCFClient();
            string result= client.HelloWCF();
            Console.WriteLine(result);
            client.Close();
            Console.Read();
        }
    }
}

  

这样就创建了一个wcf服务 



原文地址:https://www.cnblogs.com/ProDoctor/p/7600737.html