教你如何使用纯文本文件创建WCF服务

    这篇文章将教你如何不使用Visual Studio,使用纯文本文件创建一个WCF服务。

     一、编写代码:

    首先,在你的C盘创建两个txt文件。一个文件名为:ServerProgram.txt,一个文件名为:ClientProgram.txt。

    在ServerProgram.txt中输入下面代码,实现一个加法的WCF服务,代码很简单:

 

using System;
 using System.ServiceModel;

namespace SimpleWcfService
{
    class ServerProgram
    {
        static void Main(string[] args)
        {

            BasicHttpBinding binding = new BasicHttpBinding();
            Uri serviceUri = new Uri("http://localhost:8001");
            ServiceHost host = new ServiceHost(typeof(SimpleWcfService), serviceUri);
            host.AddServiceEndpoint(typeof(ISimpleWcfService), binding, "OperationService");
            host.Open();
            Console.WriteLine("服务启动");
            Console.ReadLine();
            host.Close();

        }
    }

    [ServiceContract]
    public interface ISimpleWcfService
    {
        [OperationContract]
        int Add(int a, int b);
    }

    public class SimpleWcfService : ISimpleWcfService
    {
        public int Add(int a,int b)
        {
            return a + b;
        }
    }
}

 

在ClientProgram.txt中输入下面代码来调用上面的WCF服务:

using System;
using System.ServiceModel;
using System.Windows.Forms;

namespace SimpleWcfServiceClient
{
    class ClientProgram
    {
        static void Main(string[] args)
        {
            string input;
            int a, b;
            Console.WriteLine("请输入两个整数,以逗号隔开!");
            input =Console.ReadLine();
            a = int.Parse(input.Split(',')[0]);
            b = int.Parse(input.Split(',')[1]);
            BasicHttpBinding binding = new BasicHttpBinding();
            ChannelFactory<ISimpleWcfService> factory = new ChannelFactory<ISimpleWcfService>(binding, new EndpointAddress("http://localhost:8001/OperationService"));
            ISimpleWcfService proxy = factory.CreateChannel();
            int result = proxy.Add(a,b);
            Console.WriteLine(string.Format("经过WCF服务计算,{0}加{1}原来等于{2}.",a,b, result));
            Console.ReadLine();


        }

        [ServiceContract]
        public interface ISimpleWcfService
        {
            [OperationContract]
            int Add(int a,int b);
        }
    }
}

二、编译代码:

打开Command prompt 。通过cmd命令,转到C盘下面。
1、输入下面命令编译服务端代码:
csc /r:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.ServiceModel.dll" ServerProgram.txt
2、输入下面命令编译客户端代码:
csc /r:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.ServiceModel.dll" ClientProgram.txt
3、/r:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.ServiceModel.dll"用于引入System.ServiceModel.dll

三、运行程序:
1、服务端截图


2、客户端截图:


 

总结:本文使用文本文件创建一个WCF服务。这个是我以前在服务器上测试WCF的方法,由于服务器上没安装VS,只有.net framwork。此法只适用于学习和研究,不建议在实际中使用。

aaaaaa -
共有0个回答