C#搭建一个简易的WCF服务(使用本地IP)

使用控制台应用搭建WCF

通过控制台应用程序创建

以SystemSecretService为例

  1. 新建一个ConsoleApplication,添加引用System.ServiceModel

  2. 创建一个服务接口并实现

    SystemSecretServiceImpl.cs:

    using System.ServiceModel;
    
    namespace SystemSecretService.Services
    {
        //接口对外公开的标记
        [ServiceContract]
        public partial interface ISystemSecretService
        {
        }
    }
    

    SystemSecretServiceImpl.cs:

    namespace SystemSecretService.Services.Impl
    {
        class SystemSecretServiceImpl : ISystemSecretService
        {
        }
    }
    

    P.S.接口添加成员时需加上特性[OperationContract],实现成员时可访问性设为public

  3. 在config文件中添加配置

    连接2中创建的服务接口实现类,并设置behaviorConfiguration

    name需包含命名空间和类名,baseAddress为服务器端口

    <system.serviceModel>
        <services>
            <service behaviorConfiguration="metadata" name="SystemSecretService.Services.Impl.SystemSecretService">
                <endpoint binding="basicHttpBinding" contract="SystemSecretService.Services.ISystemSecretService" />
                <host>
                    <baseAddresses>
                        <add baseAddress="http://localhost:8002/SystemSecretService" />
                    </baseAddresses>
                </host>
            </service>
        </services>
        <behaviors>
            <serviceBehaviors>
                <behavior name="metadata">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="true" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    </system.serviceModel>
    
  4. 主程序中启动(需要管理员权限)

    try
    {
        ServiceHost host;
    
        host = new ServiceHost(typeof(Services.Impl.SystemSecretService));
        host.Open();
    
        Console.WriteLine("服务已经启动!");
    }
    catch (System.Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    finally
    {
        Console.ReadLine();
    }
    

客户端连接服务器

实例采用C/S结构,客户端部分使用Winform搭建
以连接SystemSecretService为例

  1. 添加引用System.SeviceModel、System.Runtime.Serialization

  2. 创建一个静态类

    public static class WcfChannelFactory
    {
        #region WCF服务工厂
        public static T CreateServiceByUrl<T>(string url)
        {
            return CreateServiceByUrl<T>(url, "basicHttpBinding");
        }
    
        public static T CreateServiceByUrl<T>(string url, string bing)
        {
            try
            {
                if (string.IsNullOrEmpty(url)) throw new NotSupportedException("This url is not Null or Empty!");
                EndpointAddress address = new EndpointAddress(url);
                Binding binding = CreateBinding(bing);
                ChannelFactory<T> factory = new ChannelFactory<T>(binding, address);
                return factory.CreateChannel();
            }
            catch (Exception ex)
            {
                throw new Exception("创建服务工厂出现异常." + ex.Message);
            }
        }
        #endregion
    
        #region 创建传输协议
        /// <summary>
        /// 创建传输协议
        /// </summary>
        /// <param name="binding">传输协议名称</param>
        /// <returns></returns>
        private static Binding CreateBinding(string binding)
        {
            Binding bindinginstance = null;
            if (binding.ToLower() == "basichttpbinding")
            {
                BasicHttpBinding ws = new BasicHttpBinding();
                ws.MaxBufferSize = 2147483647;
                ws.MaxBufferPoolSize = 2147483647;
                ws.MaxReceivedMessageSize = 2147483647;
                ws.ReaderQuotas.MaxStringContentLength = 2147483647;
                ws.CloseTimeout = new TimeSpan(0, 30, 0);
                ws.OpenTimeout = new TimeSpan(0, 30, 0);
                ws.ReceiveTimeout = new TimeSpan(0, 30, 0);
                ws.SendTimeout = new TimeSpan(0, 30, 0);
    
                bindinginstance = ws;
            }
            else if (binding.ToLower() == "nettcpbinding")
            {
                NetTcpBinding ws = new NetTcpBinding();
                ws.MaxReceivedMessageSize = 65535000;
                ws.Security.Mode = SecurityMode.None;
                bindinginstance = ws;
            }
            else if (binding.ToLower() == "wshttpbinding")
            {
                WSHttpBinding ws = new WSHttpBinding(SecurityMode.None);
                ws.MaxReceivedMessageSize = 65535000;
                ws.Security.Message.ClientCredentialType = System.ServiceModel.MessageCredentialType.Windows;
                ws.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
                bindinginstance = ws;
            }
            return bindinginstance;
    
        }
        #endregion
    }
    
  3. 创建一个服务配置类,添加URL和服务接口

    public static string SystemSecretServiceURL = "http://localhost:8002/SystemSecretService?wsdl";
    
    public static ISystemSecretService SystemSecretProxy = WcfChannelFactory.CreateServiceByUrl<ISystemSecretService>(SystemSecretServiceURL);
    
  4. 启动服务,用浏览器启动端口,复制svcutil.exe框内链接

    f97e23e6-19c9-437b-b24b-3a364a46ceb9.png
  5. vs打开HCDCsvc->Tools->SvcUtil(没有的话百度搜索如何vs添加SvcUtil),输入4中复制内容

  6. 生成的Impl.cs复制到客户端项目中并添加

部分错误

  • 服务有零个应用程序(非基础结构)终结点。这可能是因为未找到应用程序的配置文件,或者在配置文件中未找到与服务名称匹配的服务元素,或者服务元素中未定义终结点。

    8f208282-9ec5-45fd-8581-1e0764eaab02.png

    解决办法:检查config中service的name是否按“命名空间.类”书写,以及是否写错

  • <服务名>有零个操作;协定必须至少有一个操作。

    455361ea-030a-44bc-b731-da2a74b26b88.png

    解决办法:服务接口里添加一个成员并实现

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值