c# 在自定义属性中执行代码

标签 c# asp.net-mvc attributes runtime

<分区>

Possible Duplicate:
Why does my .NET Attribute not perform an action?

你好,

这听起来像是一个非常愚蠢的问题,我不知道这里有什么可能,因为网络上的所有“自定义属性”教程都几乎相同,而且它们没有解决我想做的事情。 我已经看到一些代码是在属性类中编写的,例如:Logging with ASP.NET MVC Action Filters我想知道这段代码是如何执行的。

例如,如果我有以下代码:

public class Test
{
    [RestrictedAttribute("RegisteredMember")]
    public void DoSomething()
    {
        //this code can only be executed if the logged-in user
        //is a member of the RegisteredMember group
    }
}

那么自定义属性 RestrictedAttribute 将是这样的:

[AttributeUsage(AttributeTargets.Method)]
public class RestrictedAttribute : System.Attribute 
{
    /// <summary>
    /// Make this code restricted to users with a required role
    /// </summary>
    /// <param name="requiredRole">The role required to execute this method</param>
    public RestrictedAttribute(string requiredRole)
    {
        //validate if member is in role, else throw exception
        throw new MemberNotInRoleException(requiredRole);
    }
    public new string ToString() {
        return "Access needs to be granted";
    }

}

现在的问题是当我执行 Test.DoSomething() 方法时无法抛出 MemberNotInRoleException。

也许我只是错过了自定义属性的整个概念,请随意解释。

最佳答案

您看待属性的方式一开始听起来是对的,但请再想想。你真正在做的是装饰你的类(class)或其他任何东西,以便与之一起工作的东西可以做出决定,而不是类(class)本身可以做出决定。您可以在 MVC 中使用 actionfilter 属性的方式让我蒙上了阴影,这看起来像是在做某事,但它是挑选事件并相应地使用属性的框架。我通常会尝试将属性视为我的程序要使用的注释。

关于c# 在自定义属性中执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1176510/

相关文章:

asp.net-mvc-4 - 本地化比较属性

c# - 如何在没有属性构造函数(Reflection.Emit)的情况下将值添加到动态添加到属性的属性

c# - .NET Core 3.0 Web Api (JsonSerializer) 不序列化嵌套对象/所有对象信息

c# - Identity 如何知道密码重置 token 是否已被使用?

c# - 通过 web.config 转换保护连接字符串的建议方法

c# - .net 中 [compare ("")] 数据注释的对面?

c# - 服务器发送的事件如何与 ASP.NET MVC 一起工作?

c# - 限制 .NET 类型是否只能通过 ByVal 或 ByRef

c# - 将日期时间保存为数据库中的字符串

c# - 如何在 F# Giraffe Web API 中检索 url 编码形式?