using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Activation;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Services;
namespace TestRealProxy
{
public class SqlVerifyProxy : RealProxy
{
MarshalByRefObject _target = null;
public SqlVerifyProxy(Type type, MarshalByRefObject target)
: base(type)
{
this._target = target;
}
//覆写Invoke,处理RealProxy截获的各种消息,
//此种方式最简捷,但不能截获远程对象的激活,好在我们并不是真的要Remoting
public override IMessage Invoke(IMessage msg)
{
IMethodCallMessage call = (IMethodCallMessage)msg;
IConstructionCallMessage ctr = call as IConstructionCallMessage;
IMethodReturnMessage back = null;
//构造函数,只有ContextBoundObject(Inherit from MarshalByRefObject)对象才能截获构造函数
if (ctr != null)
{
RealProxy defaultProxy = RemotingServices.GetRealProxy(_target);
//如果不做下面这一步,_target还是一个没有直正实例化被代理对象的透明代理,
//这样的话,会导致没有直正构建对象。
defaultProxy.InitializeServerObject(ctr);
//本类是一个RealProxy,它可通过GetTransparentProxy函数得到透明代理
back = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctr, (MarshalByRefObject)GetTransparentProxy());
}
//MarshalByRefObject对象就可截获普通的调用消息,
//MarshalByRefObject对象告诉编译器,不能将其内部简单的成员函数优化成内联代码,
//这样才能保证函数调用都能截获。
else
{
IDictionary<string, object> dic = new Dictionary<string, object>();
//过滤参数
for (int i = 0; i < call.Args.Length;i++ )
{
if (call.Args[i].ToString().Contains("123"))
call.Args[i] = call.Args[i].ToString().Replace("123", "123--");
}
//dic = actionContext.ActionArguments;
//if (dic != null && dic.Count > 0)
//{
// foreach (var m in dic)
// {
// string o = m.Value;//.ToJson();
// // Utils.Filter(o);
// }
//}
System.IO.File.AppendAllText(System.Web.HttpContext.Current.Server.MapPath("~/1.txt"), string.Join(",", call.Args) + "=================");
back = RemotingServices.ExecuteMessage(_target, call);
}
return back;
}
}
//从ProxyAttribute继承,自动实现RealProxy植入
[AttributeUsage(AttributeTargets.Class)]
class SqlVerifyProxyAttribute : ProxyAttribute
{
//覆写CreateInstance函数,返回我们自建的代理
public override MarshalByRefObject CreateInstance(Type serverType)
{
MarshalByRefObject obj = base.CreateInstance(serverType);
SqlVerifyProxy proxy = new SqlVerifyProxy(serverType, obj);
return (MarshalByRefObject)proxy.GetTransparentProxy();
}
}
/// <summary>
/// 业务代码,需要继承 ContextBoundObject ,凡是调用 Test方法下的方法都会AOP
/// </summary>
[SqlVerifyProxy]
public class Test : ContextBoundObject
{
public void say(string msg)
{
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestRealProxy;
namespace TestRealProxy2.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index(string id)
{
//只要调用Test了类下的方法,都会过滤参数
Test t = new Test();
t.say(id);
return View();
}
public ActionResult About()
{
return View();
}
}
}