[英]How can I automatically configure WCF service on user's machine
I have an existing .NET application that controls external hardware. 我有一个控制外部硬件的现有.NET应用程序。 I am looking into extending some of the functionality that already exists on the PC to a smartphone app that will be used exclusively over a local network.
我正在考虑将PC上已存在的某些功能扩展到仅在本地网络上使用的智能手机应用程序。 This is not an enterprise system installed in a single location, it is a system sold to the public.
这不是安装在单个位置的企业系统,而是向公众出售的系统。 WCF looks like a great solution, but if I'm going to have to walk users through manually setting up the service, configuring IIS, etc, that's a showstopper.
WCF看起来是一个很好的解决方案,但是如果我不得不引导用户手动设置服务,配置IIS等,那就太麻烦了。 How can I programatically deploy a WCF service so it is visible on a local network?
如何以编程方式部署WCF服务,使其在本地网络上可见?
I've got it figured out. 我知道了。 There are obviously multiple hosting methods, as Code Chops pointed out.
正如Code Chops所指出的,显然有多种托管方法。 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.
我还专门使用C#,没有xml配置。 This allows me to programmatically determine the local IP address (not shown).
这使我能够以编程方式确定本地IP地址(未显示)。 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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.