的asp.net MVC应用程序
专门授权的属性,我们正努力创造一个更具体的[授权]属性的Asp.Net MVC的asp.net MVC应用程序
[AttributeUsage(AttributeTargets.All)]
public class AuthoriseUser : System.Attribute
{
public AuthoriseUser(string PermRequest)
{
//Do Some Auth.
}
}
,我们称之为像这样,
[AuthoriseUser("CanViewRoles")]
但是在调试该函数时从未被调用过。
现在我们明显在做一些非常错误的事情,我见过PostSharp,但由于项目的性质,我无法使用它。我怎么才能实现这个使用.Net?
属性不是用来扮演功能角色的。您需要在项目中使用反射来编写代码,该代码读取类[和道具,方法等]的类型元数据并查找应用于其中的属性。根据应用的属性,您可以在运行时决定如何处理。通常这是在你的库的基类中完成的。
作为我们项目中的一个示例,我们有一个名为“Searchable”的属性。此属性应用于需要包含在搜索中的业务对象的属性。当客户端调用搜索方法时,我们会过滤掉所有用Searchable属性装饰的道具,然后构造查询以在数据库上执行搜索。实际上,我们没有任何与SearchableAttribute类中的搜索功能相关的代码 - 实际上SearchableAttribute类中没有任何代码。
示例代码:
SearchableAttribute
/// <summary>
/// Holds mapping information of searchable fields of business objects.
/// </summary>
[global::System.AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public sealed class SearchableAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the SearchableAttributeAttribute class.
/// </summary>
public SearchableAttribute()
{
}
}
在业务对象的基类的方法
/// <summary>
/// Provides collection of all Searchable Fields.
/// </summary>
/// <returns>DataField collection</returns>
public IQueryable<DataField> GetSearchableDataFields()
{
PropertyInfo[] properties =
this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
var entityFields = from PropertyInfo property in properties
where property.GetCustomAttributes(typeof(SearchableAttribute), true).Length > 0
select
new DataField(
property,
(SearchableAttribute)property.GetCustomAttributes(typeof(SearchableAttribute), true)[0]);
return entityFields.AsQueryable();
}
属性用于“装饰”方法/属性/类,以便您可以为该方法提供附加/额外的含义。
通过装饰具有特定属性的方法,这并不意味着只要调用该方法就会执行“属性”。 如果你想要这样的行为,你将不得不看看代码编织器,比如PostSharp,以便为你用属性装饰的方法/属性编织附加代码。
你不需要从AuthorizeAttribute
派生出你的班级吗?请参阅Custom Authorization in the ASP.NET MVC Framework and Authorize Attribute
这似乎是一个不错的选择。 – LiamB 2009-11-27 09:38:15
.NET中的属性用于修饰类或方法,但您需要编写代码以请求此信息。例如,要验证一个类装饰有您的自定义属性,你可以使用这样的事情:
var attributes = (AuthoriseUser[])typeof(YourType)
.GetCustomAttributes(typeof(AuthoriseUser), true);
然后你可以阅读与此属性相关的元数据。
你有这样的例子吗? – LiamB 2009-11-27 09:44:57
添加代码:) :) – 2009-11-27 09:50:31
您的答案在ASP.NET MVC之外是正确的;但是,ASP.NET MVC操作过滤器是一种特殊的属性。它们是作为MVC管道的一部分执行的,并允许您处理某些事件。 http://www.asp.net/learn/mvc/tutorial-14-cs.aspx你的答案在ASP.NET MVC的上下文中是错误的。 – 2009-11-27 16:56:29