namespace LiangQ.UserAttribute
{
[System.AttributeUsage(AttributeTargets.All)]
public class AuthAttribute : ContextAttribute//contextattribute是所有上下文属性的根。
{
public string ObjectName;
//public AuthAttribute() : base("Auth") { }
public AuthAttribute(string profile) : base ("Auth")
{
this.ObjectName = profile;
}
public override void GetPropertiesForNewContext(IConstructionCallMessage ctorMsg)
{
ctorMsg.ContextProperties.Add(new AuthProperty());
//将这个自定义属性添加到AuthProperty的消息中
}
}
public class AuthProperty : IContextProperty, IContributeObjectSink
{
#region IContributeObjectSink implementation
public IMessageSink GetObjectSink(MarshalByRefObject o, IMessageSink next)
//将所提供的服务器对象的消息接收器连接到给定的接收器链前面
{
return new AuthAspect(next);
}
#endregion // IContributeObjectSink implementation
#region IContextProperty implementation
public string Name
{
get { return "AuthProperty"; }
}
public void Freeze(Context newContext)
{
}
public bool IsNewContextOK(Context newCtx)
{
return true;
}
#endregion //IContextProperty implementation
}
internal class AuthAspect : IMessageSink//定义一个消息接收器
{
internal AuthAspect(IMessageSink next)
{
m_next = next;
}
#region Private Vars
private IMessageSink m_next;
#endregion // Private Vars
#region IMessageSink implementation
public IMessageSink NextSink
{
get { return m_next; }
}
public IMessage SyncProcessMessage(IMessage msg)
{
Preprocess(msg);
IMessage returnMethod = m_next.SyncProcessMessage(msg);
return returnMethod;
}
public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
{
throw new InvalidOperationException();
}
#endregion //IMessageSink implementation
#region Helper methods
private void Preprocess(IMessage msg)
{
// We only want to process method calls
if (!(msg is IMethodMessage)) return;
IMethodMessage call = msg as IMethodMessage;
Type type = Type.GetType(call.TypeName);
string callStr = type.Name + "." + call.MethodName;
//Console.WriteLine("Security validating : {0} for {1}", callStr,Environment.UserName);
// call some security validating code
//MethodInfo m = (typeof(AttributeTest)).GetMethod(call.MethodName);
foreach(object t in call.Properties)
{
if(t is AuthAttribute)
{
AuthAttribute i = (AuthAttribute) t;
Console.WriteLine(i.ObjectName);
}
}
}
#endregion Helpers
}
}
我只是对自定义属性创建了一个新的构造函数,以接收用户的参数。
有一个问题我没有解决,就是我只能把这个属性作用到类上才可以起作用,但是如果作用到函数上就无法起作用了,还请高手指教啊!
[@more@]来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/14820420/viewspace-1016294/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/14820420/viewspace-1016294/