zoukankan      html  css  js  c++  java
  • WCF使用纯代码的方式进行服务寄宿

    服务寄宿的目的是为了开启一个进程,为WCF服务提供一个运行的环境。通过为服务添加一个或者多个终结点,使之暴露给潜在的服务消费,服务消费者通过匹配的终结点对该服务进行调用,除去上面的两种寄宿方式,还可以以纯代码的方式实现服务的寄宿工作。

    新建立一个控制台应用程序,添加System.ServiceModel库文件的引用。

    添加WCF服务接口:ISchool使用ServiceContract进行接口约束,OperationContract进行行为约束

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    using System.ServiceModel.Activation;
    
    
    namespace WcfTest.Demo3
    {
        [ServiceContract]
        public interface ISchool
        {
            [OperationContract]
            string ShowName(string Name);
        }
    }

    添加School类,实现Ishool接口:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace WcfTest.Demo3
    {
        public class School:ISchool
        {
            public string ShowName(string name)
            {
                return "Show Name " + name;
            }
        }
    }

    通过代码将ISchool接口寄宿到控制台应用程序之中。

        class Program
        {
            static void Main(string[] args)
            {
                CoreCodeOpen();
            }
    
            /// <summary>
            /// 通过代码的方式完成服务的寄宿工作
            /// </summary>
            static void CoreCodeOpen()
            {
                try
                {
                    using (ServiceHost host = new ServiceHost(typeof(School)))
                    {
                        host.AddServiceEndpoint(typeof(ISchool), new WSHttpBinding(), "http://10.0.0.217:20004/School");
                        if (host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
                        {
                            ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                            behavior.HttpGetEnabled = true;
                            behavior.HttpGetUrl = new Uri("http://10.0.0.217:20004/School/wcfapi");
                            host.Description.Behaviors.Add(behavior);
                        }
                        host.Open();
                        Console.WriteLine("寄宿到控制台应用程序,通过代码开启WCF服务");
                        Console.ReadKey();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("CoreCodeOpen Error:" + ex.Message);
                }
            }
        }

    以管理员身份运行程序>在浏览器输入http://10.0.0.217:20004/School/wcfapi>我们会得到以WSDL(网络服务描述语言-Web Services Description Language)形式体现的服务元数据

    在解决方案中新建控制台客户端,添加服务引用,输入http://10.0.0.217:20004/School/wcfapi

    找到了我们的Ischool服务接口,添加引用后进行服务的调用。

  • 相关阅读:
    [LeetCode] Binary Tree Preorder Traversal
    Linux下搭建JSP环境
    Linux系统捕获数据包流程
    如何使用Linux套接字?
    IPod在Linux下的实战
    将手机流氓软件彻底赶出去
    如何修复和检测Windows系统漏洞
    防止网络渗透措施两则
    Cisco安全防护读书笔记之一Cisco系统设备协议漏洞
    至顶网推荐-Rpm另类用法加固Linux安全
  • 原文地址:https://www.cnblogs.com/heyangyi/p/8521100.html
Copyright © 2011-2022 走看看