1using System; 2using System.Collections.Generic; 3using System.Linq; 4using System.ServiceModel.Channels; 5using System.ServiceModel.Description; 6using System.ServiceModel.Dispatcher; 7using System.Web; 8 9namespace Test 10{ 11 public class MyOperationInterceptorAttribute : Attribute, IOperationBehavior 12 { 13 public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) 14 { } 15 public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) 16 { } 17 public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation) 18 { 19 dispatchOperation.Invoker = new MyInvoker(dispatchOperation.Invoker); 20 } 21 public void Validate(OperationDescription operationDescription) 22 { } 23 } 24} 25 26using System; 27using System.Collections.Generic; 28using System.Linq; 29using System.Net; 30using System.ServiceModel; 31using System.ServiceModel.Dispatcher; 32using System.ServiceModel.Web; 33using System.Web; 34 35namespace Test 36{ 37 public class MyInvoker : IOperationInvoker 38 { 39 40 private readonly IOperationInvoker m_OldInvoker; 41 42 public MyInvoker(IOperationInvoker inner) 43 { 44 m_OldInvoker = inner; 45 } 46 47 public object Invoke(object instance, object[] inputs, out object[] outputs) 48 { 49 try 50 { 51 //这里可以进行一些权限验证 52 //do something 53 object result = m_OldInvoker.Invoke(instance, inputs, out outputs); 54 55 return result; 56 } 57 catch (Exception err) 58 { 59 outputs = new object[0]; 60 //do catch 61 return null; 62 } 63 finally 64 { 65 66 } 67 68 } 69 70 public virtual object[] AllocateInputs() 71 { 72 return m_OldInvoker.AllocateInputs(); 73 } 74 75 public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state) 76 { 77 return m_OldInvoker.InvokeBegin(instance, inputs, callback, state); 78 } 79 80 public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result) 81 { 82 83 return m_OldInvoker.InvokeEnd(instance, out outputs, result); 84 85 } 86 87 public bool IsSynchronous 88 { 89 get 90 { 91 return m_OldInvoker.IsSynchronous; 92 } 93 } 94 } 95} 96 97public class srvtest 98 { 99 [WebGet(UriTemplate = "", ResponseFormat = WebMessageFormat.Json)] 100 [MyOperationInterceptor] 101 public string Hello() 102 { 103 return "Hello" + DateTime.Now.ToString(); 104 } 105 106 [WebGet(UriTemplate = "Index", ResponseFormat = WebMessageFormat.Json)] 107 public string Index() 108 { 109 return "Index" + DateTime.Now.ToString(); 110 } 111 }
在需要拦截的方法上添加 [MyOperationInterceptor]即可,不需要拦截的就不添加