- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.ServiceModel.Channels;
- using System.ServiceModel.Description;
- using System.ServiceModel.Dispatcher;
- using System.Web;
-
- namespace Test
- {
- public class MyOperationInterceptorAttribute : Attribute, IOperationBehavior
- {
- public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
- { }
- public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
- { }
- public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
- {
- dispatchOperation.Invoker = new MyInvoker(dispatchOperation.Invoker);
- }
- public void Validate(OperationDescription operationDescription)
- { }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.ServiceModel;
- using System.ServiceModel.Dispatcher;
- using System.ServiceModel.Web;
- using System.Web;
-
- namespace Test
- {
- public class MyInvoker : IOperationInvoker
- {
-
- private readonly IOperationInvoker m_OldInvoker;
-
- public MyInvoker(IOperationInvoker inner)
- {
- m_OldInvoker = inner;
- }
-
- public object Invoke(object instance, object[] inputs, out object[] outputs)
- {
- try
- {
- //这里可以进行一些权限验证
- //do something
- object result = m_OldInvoker.Invoke(instance, inputs, out outputs);
-
- return result;
- }
- catch (Exception err)
- {
- outputs = new object[0];
- //do catch
- return null;
- }
- finally
- {
-
- }
-
- }
-
- public virtual object[] AllocateInputs()
- {
- return m_OldInvoker.AllocateInputs();
- }
-
- public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
- {
- return m_OldInvoker.InvokeBegin(instance, inputs, callback, state);
- }
-
- public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
- {
-
- return m_OldInvoker.InvokeEnd(instance, out outputs, result);
-
- }
-
- public bool IsSynchronous
- {
- get
- {
- return m_OldInvoker.IsSynchronous;
- }
- }
- }
- }
- public class srvtest
- {
- [WebGet(UriTemplate = "", ResponseFormat = WebMessageFormat.Json)]
- [MyOperationInterceptor]
- public string Hello()
- {
- return "Hello" + DateTime.Now.ToString();
- }
-
- [WebGet(UriTemplate = "Index", ResponseFormat = WebMessageFormat.Json)]
- public string Index()
- {
- return "Index" + DateTime.Now.ToString();
- }
- }
在需要拦截的方法上添加 [MyOperationInterceptor]即可,不需要拦截的就不添加