如何分析方法调用的属性?
我有一个有多种方法的对象。其中一些用 [AuthenticationRequired]
属性修饰。我应该何时以及如何检查被调用者是否经过身份验证?
这只是一个简单的 null
检查,但我不知道如何将其挂钩到实际的方法调用。我有点迷失在这里。
我应该:
- 使用 StackFrame ,确定该类调用的顶级方法,然后找出可能的身份验证问题?
- 在具有该属性的每个方法中都包含此检查吗?那么这个属性有什么用呢?
- 以某种方式挂钩我的类上的所有方法调用,确定它们是否具有该属性?
类结构大致如下:
public class Stuff
{
public void ImFine()
{
CommonMethod("fine");
}
public void ImGood()
{
CommonMethod("good");
}
[AuthenticationRequired]
public void ImTerrible()
{
CommonMethod("terrible", true); // not an optional parameter.
}
[AuthenticationRequired]
public void ImDeceased()
{
CommonMethod("dead");
}
protected void CommonMethod(string state)
{
Console.WriteLine(string.Format("I feel {0}", state));
}
protected void CommonMethod(string state, bool pet)
{
if (pet)
{
Console.WriteLine(string.Format("My pet feels {0}", state));
}
else
{
Console.WriteLine(string.Format("I feel {0}", state));
}
}
}
假设 CommonMethod 稍微复杂一些,并且一个方法不能调用另一个方法(以便每个被调用者共享一个方法)。
I have an object with several methods. Some of which are decorated with a [AuthenticationRequired]
attribute. When, and how, should I be checking whether the callee is authenticated?
This is just a simple null
check, but I don't know how to hook it to the actual method calls. I'm kind of lost here.
Do I:
- Use a StackFrame, determine the top-level method called on this class, and then figure out possible authentication issues?
- Include this check in every single method that has the attribute? What's the attribute good for, then?
- Somehow hook to all method calls on my class, figuring out whether they have the attribute?
The class structure is roughly:
public class Stuff
{
public void ImFine()
{
CommonMethod("fine");
}
public void ImGood()
{
CommonMethod("good");
}
[AuthenticationRequired]
public void ImTerrible()
{
CommonMethod("terrible", true); // not an optional parameter.
}
[AuthenticationRequired]
public void ImDeceased()
{
CommonMethod("dead");
}
protected void CommonMethod(string state)
{
Console.WriteLine(string.Format("I feel {0}", state));
}
protected void CommonMethod(string state, bool pet)
{
if (pet)
{
Console.WriteLine(string.Format("My pet feels {0}", state));
}
else
{
Console.WriteLine(string.Format("I feel {0}", state));
}
}
}
Assume CommonMethod
is barely more complex and one can't invoke the other (in order to have one method shared by every callee).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否考虑过面向方面的编程?您可以查看一些实现,即: PostSharp 或 城堡。
Have you thought about aspect oriented programming? You may take a look at some of implementations, ie: PostSharp or Castle.