Вопрос по visual-studio-2008, wcf, c#, .net – ошибка привязки mex в WCF

16

Я использую VSTS 2008 + C # + .NET 3.0. Я использую самодостаточный сервис WCF. При выполнении следующего оператора возникает следующая «привязка не найдена» ошибка. Я разместил весь файл app.config, есть идеи, что не так?

ServiceHost host = new ServiceHost(typeof(MyWCFService));

Сообщение об ошибке:

Could not find a base address that matches scheme http for the endpoint with binding MetadataExchangeHttpBinding. Registered base address schemes are [https].

Полный app.config:

<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="MyBinding"
            closeTimeout="00:00:10"
            openTimeout="00:00:20"
            receiveTimeout="00:00:30"
            sendTimeout="00:00:40"
            bypassProxyOnLocal="false"
            transactionFlow="false"
            hostNameComparisonMode="WeakWildcard"
            maxReceivedMessageSize="100000000"
            messageEncoding="Mtom"
            proxyAddress="http://foo/bar"
            textEncoding="utf-16"
            useDefaultWebProxy="false">
          <reliableSession ordered="false"
               inactivityTimeout="00:02:00"
               enabled="true" />
          <security mode="Transport">
            <transport clientCredentialType="Digest"
               proxyCredentialType="None"
               realm="someRealm" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <services>
      <service name="MyWCFService"
                behaviorConfiguration="mexServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="https://localhost:9090/MyService"/>
          </baseAddresses>
        </host>
        <endpoint address="" binding="wsHttpBinding" bindingConfiguration="MyBinding" contract="IMyService"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="mexServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
<startup><supportedRuntime version="v2.0.50727"/></startup></configuration>

Ваш Ответ

3   ответа
45

HTTPS: // & quot; - но ваш мекс-адрес "HTTP".

Если вы хотите, чтобы ваш сервис использовал https: //, вам нужно будет использоватьmexHttpsBinding также:

<services>
    <service name="MyWCFService" behaviorConfiguration="mexServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="https://localhost:9090/MyService"/>
          </baseAddresses>
        </host>
        <endpoint address="" 
                binding="wsHttpBinding" 
                bindingConfiguration="MyBinding" 
                contract="IMyService" 
        />
        <endpoint address="mex" 
                binding="mexHttpsBinding" 
                contract="IMetadataExchange" 
        />
    </service>
</services>

Марк

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceededhttp://Error: User Rate Limit Exceeded
3

Marc_s ответ

Is it possible to have IMetadataExchange for both http and https as separate endpoints?

& # XA0; marc_s & # xA0; & # ответил xA0;

you should be able to define a second base address, for http:// and use that for the http mex endpoint.

Таким образом, решение состоит в том, чтобы объявить несколько & # xA0; конечных точек с тем же & # xA0; address = & quot; mex & quot; а такжеdifferent привязки как следующие

<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />  
<endpoint contract="IMetadataExchange" binding="mexHttpsBinding" address="mex"/>

Недавно я обнаружил, что проще иметь один конфигурационный переключатель, который можно использовать для включения MEX при тестировании и отключения в режиме реального времени.

От & # xA0;http://msdn.microsoft.com/en-us/library/aa395224.aspx

It's possible to use the ServiceHostFactory class to create a custom derived from ServiceHost in the Internet Information Services (IIS custom ServiceHost that adds the ServiceMetadataBehavior, (which enables metadata publishing), even if this behavior is not explicitly added in the service’s configuration file.

 Write the imperative code that enables metadata publishing once and then reuse that code across several different services. This is accomplished by creating a new class that derives from ServiceHost and overrides the ApplyConfiguration() method to imperatively add the metadata publishing behavior.

Пример кода изСтатья MSDN Host Custom Host

//Add a metadata endpoint at each base address
//using the "/mex" addressing convention
foreach (Uri baseAddress in this.BaseAddresses)
{
    if (baseAddress.Scheme == Uri.UriSchemeHttp)
    {
        mexBehavior.HttpGetEnabled = true;
        this.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName,
                                MetadataExchangeBindings.CreateMexHttpBinding(),
                                "mex");
    }
    else if (baseAddress.Scheme == Uri.UriSchemeHttps)
    {
        mexBehavior.HttpsGetEnabled = true;
        this.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName,
                                MetadataExchangeBindings.CreateMexHttpsBinding(),
                                "mex");
    }
    else if (baseAddress.Scheme == Uri.UriSchemeNetPipe)
    {
        this.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName,
                                MetadataExchangeBindings.CreateMexNamedPipeBinding(),
                                "mex");
    }
    else if (baseAddress.Scheme == Uri.UriSchemeNetTcp)
    {
        this.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName,
                                MetadataExchangeBindings.CreateMexTcpBinding(),
                                "mex");
    }
}
13

Поскольку вы используете WS-Http, вы привязываетесь к протоколу HTTPS, поэтому вам нужно использовать правильную привязку MEX;

<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />

Похожие вопросы