public class CustomMessageFilter : MessageFilter { private string _matchData; public CustomMessageFilter(string matchData) { this._matchData = matchData; } public override bool Match(System.ServiceModel.Channels.Message message) { return message.Headers.Action.IndexOf(this._matchData) > -1; } public override bool Match(System.ServiceModel.Channels.MessageBuffer buffer) { throw new NotImplementedException(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ServiceModel.Dispatcher; using System.ServiceModel; namespace WcfRoutingService { public class CustomerFilter : EndpointNameMessageFilter { private string _matchData; public CustomerFilter(string matchData) : base(matchData) { _matchData = matchData; } public override bool Match(System.ServiceModel.Channels.Message message) { var username = OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name; var usernameWithoutDomain = username.Split('\\')[1]; if (message.Headers.Action.StartsWith("http://tempuri.org/IService1/")) { if (usernameWithoutDomain == "Foo") { return base.Match(message); } } else if (message.Headers.Action.StartsWith("http://tempuri.org/IService2/")) { if (usernameWithoutDomain == "Bar") { return base.Match(message); } } return false; } public override bool Match(System.ServiceModel.Channels.MessageBuffer buffer) { return base.Match(buffer); } } }修改Routing Service的配置文件中 routing/filters/filter 里的内容:
<filters> <filter name="Service1Filter" filterType="Custom" customType="WcfRoutingService.CustomerFilter, WcfRoutingService" filterData="service1Endpoint" /> <filter name="Service2Filter" filterType="Custom" customType="WcfRoutingService.CustomerFilter, WcfRoutingService" filterData="service2Endpoint" /> </filters>将 filterType 改为 Custom, customType 指向上面的实现类。整体如下图:
客户端调用:
class Program { static void Main(string[] args) { Action<string, string> testWithUser = (username, passwd) => { var credential = new NetworkCredential(); credential.Domain = "P-FANGXING"; credential.UserName = username; credential.Password = passwd; try { // call service1 using (var service1client = new WcfService1.Service1Client("service1Endpoint")) { service1client.ClientCredentials.Windows.ClientCredential = credential; var result = service1client.GetData(300); Console.WriteLine(result); } } catch (Exception ex) { Console.WriteLine("Service1 -- User[{0}] Error.", username); } try { // call service2 using (var service2client = new WcfService2.Service2Client("service2Endpoint")) { service2client.ClientCredentials.Windows.ClientCredential = credential; var result = service2client.GetData(100); Console.WriteLine(result); } } catch (Exception ex) { Console.WriteLine("Service2 -- User[{0}] Error.", username); } }; // UserA calling... testWithUser("Foo", "abc@123"); // UserB calling... testWithUser("Bar", "abc@123"); Console.Read(); } }