C# 在没有App.config的情况下运行wcf服务不会';行不通

C# 在没有App.config的情况下运行wcf服务不会';行不通,c#,.net,web-services,wcf,self-hosting,C#,.net,Web Services,Wcf,Self Hosting,我在控制台应用程序中创建简单的wcf主机。它不起作用,异常也毫无意义:/ 异常看起来非常奇怪: “合同说明‘IFooService’没有任何操作;合同 必须至少有一个操作。“ 因为,这是代码,我有一个操作: [ServiceContract] public interface IFooService { [OperationContract] void DoNothing(); [OperationContract] int GetFoo(int i); }

我在控制台应用程序中创建简单的wcf主机。它不起作用,异常也毫无意义:/ 异常看起来非常奇怪:

“合同说明‘IFooService’没有任何操作;合同 必须至少有一个操作。“

因为,这是代码,我有一个操作:

[ServiceContract]
public interface IFooService
{
    [OperationContract]
    void DoNothing();

    [OperationContract]
    int GetFoo(int i);
}

public class FooService : IFooService
{
    public void DoNothing()
    {
    }

    public int GetFoo(int i)
    {
        return i + 1;
    }
}

class Program
{
    static void Main(string[] args)
    {
        try
        {
            string address = "http://localhost:9003/FooService";
            Uri addressBase = new Uri(address);

            var svcHost = new ServiceHost(typeof(FooService), addressBase);

            BasicHttpBinding bHttp = new BasicHttpBinding();

            Type contractType = typeof(IFooService);
            ContractDescription contractDescription = new ContractDescription(contractType.Name);
            contractDescription.ProtectionLevel = ProtectionLevel.None;
            contractDescription.ContractType = contractType;
            contractDescription.ConfigurationName = contractType.FullName;
            contractDescription.SessionMode = SessionMode.NotAllowed;

            svcHost.AddServiceEndpoint(new ServiceEndpoint(contractDescription, bHttp, new EndpointAddress(address)));

            svcHost.Open();
            Console.WriteLine("\n\nService is Running as >> " + address);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
        Console.ReadKey();
    }
}
这基本上是完整的代码。App.config保持不变:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
</configuration>

为什么需要使用合同描述?我想它会在配置文件中查找设置。 您可以执行以下操作(使用AddServiceEndpoint方法而不使用ContractDescription):


顺便说一句,您可以在这里找到一些库,用于在没有app.config文件的情况下配置WCF服务:

如果您没有在配置文件中提供端点,我相信您必须向ServiceHost添加端点。请参阅
AddServiceEndpoint
调用:

Uri baseAddr = new Uri("http://localhost:8000/WCFService1");
ServiceHost localHost = new ServiceHost(typeof(CalculatorService), baseAddr);

try
{
localHost.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), "CalculatorService");

ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
localHost.Description.Behaviors.Add(smb);

localHost.Open();
Console.WriteLine("Service initialized.");
Console.WriteLine("Press the ENTER key to terminate service.");
Console.WriteLine();
Console.ReadLine();

localHost.Close();
}
catch (CommunicationException ex)
{
Console.WriteLine("Oops! Exception: {0}", ex.Message);
localHost.Abort();
}

以上内容来自Microsoft示例:

这是一个很好的起点。尽管如此。。。目前尚不清楚需要在代码中添加哪些内容才能使下面的app.config内容冗余:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <services>
      <service name="GettingStartedLib.CalculatorService">
        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8000/GettingStarted/CalculatorService" />
          </baseAddresses>
        </host>
        <!-- Service Endpoints -->
        <!-- Unless fully qualified, address is relative to base address supplied above -->
        <endpoint address="" binding="wsHttpBinding" contract="GettingStartedLib.ICalculator">
          <!-- 
              Upon deployment, the following identity element should be removed or replaced to reflect the 
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity 
              automatically.
          -->
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <!-- Metadata Endpoints -->
        <!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. --> 
        <!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, 
          set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
          <!-- To receive exception details in faults for debugging purposes, 
          set the value below to true.  Set to false before deployment 
          to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

</configuration>


您的Interbase
iFoosService
中的方法不应该也是公共的吗?@VDN否,接口成员不能是私有的或公共的。不是这个案子,谢谢!真管用!谢谢你的链接,我会仔细看看。
    static void Main(string[] args)
    {
        try
        {
            string address = "http://localhost:9003/FooService";
            Uri addressBase = new Uri(address);

            var svcHost = new ServiceHost(typeof(FooService), addressBase);

             BasicHttpBinding bHttp = new BasicHttpBinding();

            //Type contractType = typeof(IFooService);
            //ContractDescription contractDescription = new ContractDescription(contractType.Name);
            //contractDescription.ProtectionLevel = ProtectionLevel.None;
            //contractDescription.ContractType = contractType;
            //contractDescription.ConfigurationName = contractType.FullName;
            //contractDescription.SessionMode = SessionMode.NotAllowed;
            //svcHost.AddServiceEndpoint(new ServiceEndpoint(contractDescription, bHttp, new EndpointAddress(address)));

            svcHost.AddServiceEndpoint(typeof(IFooService).ToString(), bHttp, address);

            svcHost.Open();
            Console.WriteLine("\n\nService is Running as >> " + address);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
        Console.ReadKey();
    }
Uri baseAddr = new Uri("http://localhost:8000/WCFService1");
ServiceHost localHost = new ServiceHost(typeof(CalculatorService), baseAddr);

try
{
localHost.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), "CalculatorService");

ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
localHost.Description.Behaviors.Add(smb);

localHost.Open();
Console.WriteLine("Service initialized.");
Console.WriteLine("Press the ENTER key to terminate service.");
Console.WriteLine();
Console.ReadLine();

localHost.Close();
}
catch (CommunicationException ex)
{
Console.WriteLine("Oops! Exception: {0}", ex.Message);
localHost.Abort();
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <services>
      <service name="GettingStartedLib.CalculatorService">
        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8000/GettingStarted/CalculatorService" />
          </baseAddresses>
        </host>
        <!-- Service Endpoints -->
        <!-- Unless fully qualified, address is relative to base address supplied above -->
        <endpoint address="" binding="wsHttpBinding" contract="GettingStartedLib.ICalculator">
          <!-- 
              Upon deployment, the following identity element should be removed or replaced to reflect the 
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity 
              automatically.
          -->
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <!-- Metadata Endpoints -->
        <!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. --> 
        <!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, 
          set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
          <!-- To receive exception details in faults for debugging purposes, 
          set the value below to true.  Set to false before deployment 
          to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

</configuration>