0

我在 C# 中有一个身份验证属性

public class JwtAuthenticationAttribute : Attribute, IAuthenticationFilter
{
    public string Realm { get; set; }
    public bool AllowMultiple => false;
    public User User { get; set; }

    public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        //authentication stuff
        this.User = GetUserFromDB();
       //more code
    }
.... more code

我使用它在 web api 控制器中进行身份验证:

[Authorize]
[JwtAuthentication]
public class AccesosController : ApiController
{
   public IHttpActionResult DoSomethingAuthenticated(){
       //how to get the user from the [JwAuthentication] attribute?
   }
}

如何从方法中的属性中获取 User 属性?我需要这个属性,因为它有一些其他信息,我需要在我的方法中处理一些其他信息。

我知道在令牌中我可以获取用户 ID 并将对象查询到数据库但我不想这样做,因为我会重复代码(在属性中查询用户)并且我需要使用用户的信息在我的应用程序的每个方法中。

我希望我已经解释了自己,并为我糟糕的英语感到抱歉

提前致谢 :)

4

1 回答 1

0

您可以使用反射访问应用于类的属性:

User user = GetType().GetCustomAttribute<JwtAuthenicationAttribute>()?.User;

以下内容还将为您提供IEnumerable类的自定义属性:

GetType().GetCustomAttributes()

我要补充一点,使用这样的属性似乎不是一个很好的用例,更多关于这里

于 2018-02-02T23:53:36.113 回答