使用ServiceHost.AddServiceEndpoint添加自定义ProtoEndpointBehavior时,出现以下异常:



代码是这样的:

ServiceHost serviceHost = null;
Console.WriteLine("Creating service " + serviceType.FullName);
serviceHost = new MyServiceHost(serviceType, new Uri(uri));

var endPointAddress = "";

HttpBindingBase binding = null;
if (secureConnectionSettings != null && secureConnectionSettings.Enabled)
{
    Console.WriteLine("Setting certificates");
    X509Store store = new X509Store(secureConnectionSettings.CertificateStore, secureConnectionSettings.CertificateLocation);
    store.Open(OpenFlags.ReadOnly);
    X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByThumbprint, secureConnectionSettings.Thumbprint, true);
    store.Close();

    if (certs.Count > 0)
        serviceHost.Credentials.ServiceCertificate.SetCertificate(secureConnectionSettings.CertificateLocation,
                                                                secureConnectionSettings.CertificateStore,
                                                                X509FindType.FindByThumbprint,
                                                                secureConnectionSettings.Thumbprint);
    else
        throw new Exception("Could not finde certificate with thumbprint " + secureConnectionSettings.Thumbprint);

    endPointAddress = uri + "/BinaryHttpsProto";
    binding = CreateNetHttpsBinding(secureConnectionSettings);
}
else
{
    endPointAddress = uri + "/BinaryHttpProto";
    binding = CreateNetHttpBinding();
}

var endpoint = new System.ServiceModel.Description.ServiceEndpoint(new System.ServiceModel.Description.ContractDescription(typeof(IMyClientService).FullName),
    binding,
    new EndpointAddress(endPointAddress));

endpoint.EndpointBehaviors.Add(new ProtoBuf.ServiceModel.ProtoEndpointBehavior());
serviceHost.AddServiceEndpoint(endpoint);

Console.WriteLine("Starting service...");
serviceHost.Open();
Console.WriteLine("Service started successfully (" + uri + ")");
return serviceHost;

我习惯在这样的配置文件中设置:
  <endpointBehaviors>
    <behavior name="protoEndpointBehavior">
      <protobuf />
    </behavior>
  </endpointBehaviors>

现在,我需要将其添加到代码中。

怎么了?

最佳答案

这是known bug,并且有解决方法。

获取ContractDescription的实例时,请使用静态方法ContractDescription.GetContract(Type)代替直接的ContractDescription()构造函数:

var endpoint = new System.ServiceModel.Description.ServiceEndpoint(System.ServiceModel.Description.ContractDescription.GetContract(typeof(IMyClientService)),
    binding,
    new EndpointAddress(endPointAddress));

我能够重现您的问题,并且此变通办法对我有用。

10-06 11:37