您可以通过添加实现"IWsdlExportExtension"的新行为来动态更新WSDL元数据中的WCF终结点地址。
public class HostNameAddressBehavior : Attribute, IWsdlExportExtension, IEndpointBehavior, IServiceBehavior
{
public void AddBindingParameters(ServiceEndpoint endpoint,
BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint,
ClientRuntime clientRuntime)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint,
EndpointDispatcher endpointDispatcher)
{
}
public void Validate(ServiceEndpoint endpoint)
{
}
public void AddBindingParameters(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints,
BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase)
{
}
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
public void ExportContract(WsdlExporter exporter,
WsdlContractConversionContext context)
{
}
public void ExportEndpoint(WsdlExporter exporter, WsdlEndpointConversionContext context)
{
var address = "YOUR_ENDPOINT";
context.Endpoint.Address = new System.ServiceModel.EndpointAddress(address);
XmlSchemaSet schemaSet = exporter.GeneratedXmlSchemas;
foreach (System.Web.Services.Description.ServiceDescription wsdl in exporter.GeneratedWsdlDocuments)
{
foreach (XmlSchema schema in wsdl.Types.Schemas)
{
ChangeSchemaLocation(schemaSet, schema, address);
}
}
}
private void ChangeSchemaLocation(XmlSchemaSet xmlSchemaSet, XmlSchema xsdDoc, string address)
{
foreach (XmlSchemaExternal external in xsdDoc.Includes)
{
if ((external != null) && string.IsNullOrEmpty(external.SchemaLocation))
{
string str = (external is XmlSchemaImport) ? ((XmlSchemaImport)external).Namespace : xsdDoc.TargetNamespace;
foreach (XmlSchema schema in xmlSchemaSet.Schemas(str ?? string.Empty))
{
if (schema != xsdDoc)
{
external.SchemaLocation = address + "/?xsd=xsd0";
break;
}
}
continue;
}
}
}
}
通过代码或配置文件添加新行为。
通过代码:
var endpoint = listener.ServiceHost.Description.Endpoints.First()
endpoint.Behaviors.Add(new HostNameAddressBehavior())
或者
通过配置:
创建扩展:
public class HostNameAddressBehaviorExtension : BehaviorExtensionElement
{
public override Type BehaviorType
{
get
{
return typeof(HostNameAddressBehavior);
}
}
protected override object CreateBehavior()
{
return new HostNameAddressBehavior();
}
}
接着添加:
<extensions>
<behaviorExtensions>
<add name="hostNameAddress" type="YourService.HostNameAddressBehaviorExtension, YourService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</behaviorExtensions>
</extensions>