0

我有一个控制外部硬件的现有 .NET 应用程序。我正在考虑将 PC 上已经存在的一些功能扩展到智能手机应用程序,该应用程序将专门通过本地网络使用。这不是安装在单个位置的企业系统,而是向公众出售的系统。WCF 看起来是一个很好的解决方案,但如果我必须引导用户手动设置服务、配置 IIS 等,那就太棒了。如何以编程方式部署 WCF 服务,使其在本地网络上可见?

4

2 回答 2

1

WCF 可以以几种不同的方式托管。是一篇很棒的文章,应该可以帮助您前进。您可以跳转到名为“探索您的托管选项”的部分。

于 2013-10-15T14:56:33.983 回答
0

I've got it figured out. There are obviously multiple hosting methods, as Code Chops pointed out. For my requirements, I just need a self hosted solution that is running when the program I'm extending is running. I also used C# exclusively, with no xml configuration. This allows me to programmatically determine the local IP address (not shown). This all runs in a normal console app.

    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);
            }

        }


    }
于 2013-10-15T21:51:31.387 回答