以下实现的目标是:
localhost:6677/Services/China
localhost:6677/Services/USA
localhost:6677/Services/...
以上所有调用都走到Service方法中,因为支持的国家是未知的,不能写成方法,并且请求的schame已经确定,不能再做修改,所以就有了以下实现:
定义Service Interface,包含一个方法Service.
代码 比较简单,只是重写OperationSelector属性,返回所有请求到方法"Service"(大小区分)
public class RouteBehaviorExtension : BehaviorExtensionElement
{
public override Type BehaviorType
{
get { return typeof(RouteBehavior); }
}
protected override object CreateBehavior()
{
return new RouteBehavior();
}
}
public class RouteBehavior : Attribute, IEndpointBehavior
{
private _operationSelector;
public RouteBehavior()
{
_operationSelector = new Router();
}
public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.OperationSelector = _operationSelector;
}
public void Validate(ServiceEndpoint endpoint)
{
}
}
internal class Router : IDispatchOperationSelector
{
public string SelectOperation(ref Message message)
{
return "Service";
}
}
配置:
添加RouteBehaviorExtension,并加该Behavior到EndpointBehaviors(注意Behavior的顺序,从上而下依次执行的)
取第二个参数:
OperationContext.Current.IncomingMessageHeaders.To.Segments[2]