【问题标题】:ServiceHost only supports class service typesServiceHost 仅支持类服务类型
【发布时间】:2012-04-09 10:42:51
【问题描述】:

我有一个名为 WcfService2 的服务(我知道原来的),它有一个带有公共接口的 IService.cs 文件:

namespace WcfService2
{
    [ServiceContract]
    public interface IService1
    {    
        [OperationContract]
        [WebGet(UriTemplate = "/{value}")]
        string GetData(string value);            
    }
}

然后我有我的公共类 Service1.svc.cs 文件,它返回一个字符串,如下所示:

namespace WcfService2
{
    public class Service1 : IService1
    {
        public string GetData(string value)
        {
            return string.Format("You entered: {0}", value);
        }
    }
}

我现在正在尝试使用这样的控制台应用来托管此服务:

namespace Host
{
    class Program
    {
        static void Main(string[] args)
        {
            WebHttpBinding binding = new WebHttpBinding();
            WebServiceHost host =
            new WebServiceHost(typeof(IService1));
            host.AddServiceEndpoint(typeof(IService1),
            binding,
            "http://localhost:8000/Hello");
            host.Open();
            Console.WriteLine("I DONT LIKE REST!");
            Console.WriteLine("Press <RETURN> to KILL REST FOR GOOD");
            Console.ReadLine();
        }
    }
}

但是我运行后报错:

ServiceHost 仅支持类服务类型。

所以这显然与我的 IService 是公共接口类型有关。但是我不知道如何创建它,当我第一次创建WCF Service application 时,它会为您提供两个标准文件 IService 和 Service.svc 文件,如果我删除其中一个或,并且仅在我尝试添加时在一个类中实现此解决方案本地灵魂中的网络服务没有找到。

有没有办法修改主机代码?

【问题讨论】:

标签: c# .net wcf exception-handling wcf-rest


【解决方案1】:

我建议你改变这个:

WebServiceHost host = new WebServiceHost(typeof(IService1));

到这里:

WebServiceHost host = new WebServiceHost(typeof(Service1));

【讨论】:

  • 如果我这样做,我会收到此错误:The contract type WcfService2.Service1 is not attributed with ServiceContractAttribute. In order to define a valid contract, the specified type (either contract interface or service class) must be attributed with ServiceContractAttribute.
  • @Garrith:发布的代码不应该出现第一个错误。您关于删除文件的胡言乱语可能在其中起作用。
  • 阅读此答案的任何人另请参阅:stackoverflow.com/questions/9864006/… 注意 WebServiceHost 是 Service1 而 AddServiceEndpoint 是 IService1!
  • 这怎么可能是一个答案?它会导致contract type WcfService2.Service1 is not attributed with ServiceContractAttribute 错误,就像@GarrithGraham 说的那样
【解决方案2】:

您应该使用实现服务的类创建 WebServiceHost;

WebServiceHost host = new WebServiceHost(typeof(Service1));

阅读here 获取示例。

【讨论】:

  • 请参阅 Will Marcouliers 回答下的回复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多