授权服务.Authorization Service
.net 框架为我们提供了 System.Security.Permissions.SecurityAttribute 特性类,
该类支持通过为类中的方法标注特性标签的方式,来实施按角色划分级别的安全授权方案。
为了使业务组件的访问权限声明从业务组件本身分离出来,模块设计使用了.net特性(.net attribute)
和.net声明性安全权限(.net declarative security permission)模型这两项技术。
.net 特性
为类和方法标注特性只是提供了类和方法的相关信息,至于如何使用这些信息,则取决于类和方法的用户。
.net框架提供了一些预定义特性,.net编译器和CLR通常会使用这些预定义特性中的信息来执行某些操作。
原生特性对象(native attribute object) ?
自定义特性需继承自Attribute或其子类。Nunit的测试属性类:
[AttributeUsage(AttributeTargets.Class, AllowMultiple
=
false
, Inherited
=
true
)]
public
sealed
class
TestFixtureAttribute : Attribute
...
{ private string description; /**//// <summary> /// Descriptive text for this fixture /// </summary> public string Description ...{ get ...{ return description; } set ...{ description = value; } } }
在代码中使用自定义的属性:
[TestFixture] [Obsolete(
"
use TestFixture attribute instead of inheritance
"
,
false
)]
public
class
TestCase : Assertion
...
{ /**//// <summary> /// SetUp method /// </summary> [SetUp] [Obsolete("use SetUp attribute instead of naming convention",false)] protected virtual void SetUp() ...{} /**//// <summary> /// TearDown method /// </summary> [TearDown] [Obsolete("use TearDown attribute instead of naming convention",false)] protected virtual void TearDown() ...{} }
已知一个程序中使用了某属性,我们如何处理这个程序,如何使用属性提供的信息:
private
static
string
GetDescription(MethodInfo method)
...
{ Type testAttr = typeof(NUnit.Framework.TestAttribute); object[] attributes = method.GetCustomAttributes(testAttr, false); string description = null; if(attributes.Length == 1) ...{ NUnit.Framework.TestAttribute attribute = (NUnit.Framework.TestAttribute)attributes[0]; description = attribute.Description; } return description; }