调用服务时出现InvalidOperationException

Bla*_*e27 3 .net c# service invalidoperationexception

合同类型HelloIndigo.Service未归属于ServiceContractAttribute.为了定义有效的合同,必须使用ServiceContractAttribute来声明指定的类型(合同接口或服务类).

我构建了一个库类,并在控制台应用程序中引用了该类.

图书馆类:

namespace HelloIndigo
{
  public class Service : IHelloIndigoService
  {
      public string HelloIndigo()
      {
        return "Hello Indigo";
      }
  }

  [ServiceContract(Namespace = "http://www.thatindigogirl.com/samples/2006/06")]
  interface IHelloIndigoService
  {
    [OperationContract]
    string HelloIndigo();
  }
}
Run Code Online (Sandbox Code Playgroud)

控制台应用程序:

namespace Host
{
  class Program
  {
    static void Main(string[] args)
    {
      using (ServiceHost host = new ServiceHost(typeof(HelloIndigo.Service), 
                                    new Uri("http://localhost:8000/HelloIndigo")))
      {
        host.AddServiceEndpoint(typeof(HelloIndigo.Service),
                                    new BasicHttpBinding(),"Service");
        host.Open();
        Console.WriteLine("Press enter to terminate the host service");
        Console.ReadLine();
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

And*_*bel 7

添加端点时,应提供合同接口:

host.AddServiceEndpoint(typeof(HelloIndigo.IHelloIndigoService),
                                new BasicHttpBinding(),"Service");
Run Code Online (Sandbox Code Playgroud)