簡體   English   中英

如何自我托管WCF服務並在不同系統中進行外部訪問

[英]How to do self hosting a wcf service and access it outside in different system

我的要求是我想在開發該服務器的服務器外部訪問wcf服務。 我需要進行自我托管,而我們那里沒有IIS,因此我需要進行tcp托管。 Windows服務主機創建了一些問題。 我想從另一台機器上訪問它。 請分享任何鏈接或演示應用程序將非常棒。

我創建了一個輔助方法,該方法以URI作為參數來承載我的WCF服務,以下是該方法:

 public ServiceHost CreateService(Uri baseAddress)
        {
            // create the net.tcp binding for the service endpoint
            NetTcpBinding ntcBinding = new NetTcpBinding();
            ntcBinding.Security.Mode = SecurityMode.None;
            System.ServiceModel.Channels.Binding tcpBinding = ntcBinding;

            // create the service host and add the endpoint
            ServiceHost host = new ServiceHost(typeof(RMS.Gateway.Services.RiskLinkService), baseAddress);

            host.Opening += new EventHandler(host_Opening);
            host.Opened += new EventHandler(host_Opened);
            host.Closing += new EventHandler(host_Closing);
            host.Closed += new EventHandler(host_Closed);
            host.Faulted += new EventHandler(host_Faulted);
            host.UnknownMessageReceived += new EventHandler<UnknownMessageReceivedEventArgs>(host_UnknownMessageReceived);

            // Check to see if the service host already has a ServiceMetadataBehavior
            ServiceMetadataBehavior smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>();

            // If not, add one
            if (smb == null)
                smb = new ServiceMetadataBehavior();

            //smb.HttpGetEnabled = true;

            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;

            host.Description.Behaviors.Add(smb);

            // Add MEX endpoint
            host.AddServiceEndpoint(
              ServiceMetadataBehavior.MexContractName,
              MetadataExchangeBindings.CreateMexTcpBinding(),
              "mex"
            );

            host.AddServiceEndpoint(typeof(RAE.Entities.ServiceInterfaces.IRiskLinkService), ntcBinding, string.Empty);

            host.Open();

            return host;
        }

然后從測試控制台應用程序中,我使用此方法啟動托管,可以在Windows服務中以類似的方式完成托管,在生產環境中,我們將進行托管,但就目前而言,為了進行簡單調試,我們將托管在控制台應用程序中:)

Uri baseAddress = new Uri(ConfigurationManager.AppSettings["serviceURL"]);

        // Create the ServiceHost.
        using (ServiceHost host = serviceFactory.CreateService(baseAddress))
        {
            System.Console.WriteLine("The service is ready at {0}", baseAddress);
            System.Console.WriteLine("Press <Enter> to stop the service.");
            System.Console.ReadLine();

            // Close the ServiceHost.
            host.Close();
        }

如您所見,NetTcpBinding是在運行時通過代碼創建的,它可以正常工作,並且我們可以從網絡中的其他計算機訪問和使用WCF端點。

希望微軟的這一循序漸進的指南可以幫助您托管wcf服務和使用該服務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM