【发布时间】:2019-08-01 23:17:34
【问题描述】:
我正在尝试在控制台应用程序中实现自托管 WCF 服务。第一步是我尝试先实现一个 helloworld 应用程序。但是,似乎我无法引用 System.ServiceModel 中的关键字或类。谁能告诉我我做错了什么?下面是我的代码。现在找不到关键字“ServiceHost”。
using System;
using System.ServiceModel;
namespace selfHost
{
[ServiceContract]
public interface IHelloWorldService
{
[OperationContract]
string SayHello(string name);
}
public class HelloWorldService : IHelloWorldService
{
public string SayHello(string name)
{
return string.Format("Hello, {0}", name);
}
}
class Program
{
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:8080/hello");
// Create the ServiceHost.
using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))
{
// Enable metadata publishing.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(smb);
// Open the ServiceHost to start listening for messages. Since
// no endpoints are explicitly configured, the runtime will create
// one endpoint per base address for each service contract implemented
// by the service.
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();
}
}
}
}
【问题讨论】:
-
这是一个意外行为。 ServiceHost 似乎是一个非常古老的东西,一直追溯到 Framework 1.1 和整个 Core。所以我们必须寻找更难调试的情况:也许解析出错了,它甚至不能告诉你哪里有错误了?还有其他编译器错误吗? |您是否将正确的 .dll 添加到项目参考中。我怀疑大多数控制台应用程序默认添加 System.ServiceModel.dll。但是,它应该已经在 using 指令上抱怨了。 |也许这是 Visual Studio 中的一个错误。毕竟它也是一个程序。
-
您是否尝试过使用
System.ServiceModel.ServiceHost的完全限定名称? -
嗨@Christopher 我也尝试了完全限定名称,但它仍然有相同的编译错误。
-
这会在源代码中留下一个一般错误——我在这里看不到——它严重影响了解释,它无法告诉你它在哪里出错。或者IDE中的一些错误。应该有一种方法可以对项目进行干净的重建,只是为了摆脱任何可能损坏并导致此问题的临时数据。
标签: c# visual-studio console-application self-hosting