簡體   English   中英

如何在用戶計算機上自動配置WCF服務

[英]How can I automatically configure WCF service on user's machine

我有一個控制外部硬件的現有.NET應用程序。 我正在考慮將PC上已存在的某些功能擴展到僅在本地網絡上使用的智能手機應用程序。 這不是安裝在單個位置的企業系統,而是向公眾出售的系統。 WCF看起來是一個很好的解決方案,但是如果我不得不引導用戶手動設置服務,配置IIS等,那就太麻煩了。 如何以編程方式部署WCF服務,使其在本地網絡上可見?

WCF可以通過幾種不同的方式托管。 是一篇很棒的文章,應該可以幫助您。 您可以跳到“探索托管選項”部分。

我知道了。 正如Code Chops所指出的,顯然有多種托管方法。 對於我的需求,我只需要一個自托管的解決方案即可在要擴展的程序運行時運行。 我還專門使用C#,沒有xml配置。 這使我能夠以編程方式確定本地IP地址(未顯示)。 這些都可以在普通控制台應用程序中運行。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    using System.ServiceModel.Description;
    using System.ServiceModel.Web;


    namespace SelfHost
    {
        class Program
        {
            static void Main(string[] args)
            {     
                string localIP = "192.168.1.5";
                string port = "8001";
                Uri baseAddress = new Uri("http://" + localIP + ":" + port + "/hello");

                using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))
                {                       
                    ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                    smb.HttpGetEnabled = true;
                    smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                    host.Description.Behaviors.Add(smb);
                    host.AddServiceEndpoint(typeof(IHelloWorldService), new WebHttpBinding(), "");
                    host.Description.Endpoints[0].Behaviors.Add(new WebHttpBehavior { HelpEnabled = true });                
                    host.Open();

                    Console.WriteLine("The service is ready at {0}", baseAddress);
                    Console.WriteLine("Press <Enter> to stop the service.");
                    Console.ReadLine();

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

        [ServiceContract]
        public interface IHelloWorldService
        {
            [OperationContract]
            [WebGet(UriTemplate = "SayHello/{name}")]
            string SayHello(string name);

            [OperationContract]
            [WebGet(UriTemplate = "SayGoodbye/{name}")]
            string SayGoodbye(string name);
        }

        public class HelloWorldService : IHelloWorldService
        {
            public string SayHello(string name)
            {
                return string.Format("Hello, {0}", name);
            }

            public string SayGoodbye(string name)
            {
                return string.Format("Goodbye, {0}", name);
            }

        }


    }

暫無
暫無

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

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