如何将方法参数插入自定义属性

Dav*_*vid 13 c# custom-attributes

我有一个名为AuthoriseAttribute的自定义属性,其构造函数如下所示:

public AuthoriseAttribute(int userId)
{
  .. blah
}
Run Code Online (Sandbox Code Playgroud)

这与一个这样的方法一起使用GetUserDetails():

[Authorise(????????)]
public UserDetailsDto GetUserDetails(int userId)
{
  .. blah
}
Run Code Online (Sandbox Code Playgroud)

在运行时,Authorize属性的存在会导致执行某些授权代码,这需要用户的ID.显然,这可以从GetUserDetails()方法的参数中提取,但这意味着授权代码取决于方法的参数被赋予特定名称.

我希望能够将userId参数的实际值传递给属性,以便授权代码使用传递给属性的值(即不是方法参数),其名称已知.

像这样的东西(不起作用):

[Authorise(userId)]
public UserDetailsDto GetUserDetails(int userId)
{
  .. blah
}
Run Code Online (Sandbox Code Playgroud)

这样的事情可能吗?

Ale*_*lex 18

这里一个办法做到这一点_in ASP.NET MVC_与行动的方法(不是一般的属性)

public class CustomAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        int userId = (int)filterContext.ActionParameters["userId"];
    }
}
Run Code Online (Sandbox Code Playgroud)


Kei*_*thS 15

让vcsjones评论答案,这是不可能的.

属性是元数据; 它们在编译时被编译到程序集中,并且在运行时不会更改.因此,传递给属性的任何参数都必须是常量; 文字,常量变量,编译器定义等

这样做的一种方法是使用像PostSharp这样的框架或使用Unity Framework等自己滚动自己的属性作为AOP元素.这将允许您通过使用属性修饰它来将"拦截器"附加到方法,然后,它将在属性中运行代码,并且还将了解如何调用方法,包括参数值.看看这个博客:http://www.progware.org/Blog/post/Interception-and-Interceptors-in-C-( Aspect-oriented-programming) .aspx

  • 我不会说这是偷东西.+1用于评论并将其转化为有用的答案. (10认同)