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

标签 c# custom-attributes

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

public AuthoriseAttribute(int userId)
{
  .. blah
}

这与名为 GetUserDetails() 的方法一起使用,如下所示:

[Authorise(????????)]
public UserDetailsDto GetUserDetails(int userId)
{
  .. blah
}

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

我希望能够将 userId 参数的实际值传递到属性中,以便授权代码使用传递到属性中的值(即不是方法参数), 其名字广为人知。

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

[Authorise(userId)]
public UserDetailsDto GetUserDetails(int userId)
{
  .. blah
}

这样的事情可能吗?

最佳答案

有一种方法可以_in ASP.NET MVC_使用操作方法(通常不使用属性)

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

关于c# - 如何将方法参数插入自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10435403/

相关文章:

c# - C#如何计算段落中某个单词的个数

具有自定义属性的 Android 自定义 View

c# - 我们如何使用自定义属性为字段赋值?

c# - 在自定义属性中传递自定义参数 - ASP.NET MVC

c# - 发布时混淆源代码 (C#)

c# - ResetBindings() 不更新 BindingSource

c# - unity texture2d EncodeToJPG 透明黑色

c# - 使用 System.Drawing.DrawLine 从控制台应用程序绘制多条线条/形状

c# - 通过自定义属性获取枚举(通用)

c# - 使用自定义属性跳过body方法