【问题标题】:How to get property from method attribute C#如何从方法属性C#中获取属性
【发布时间】:2018-07-13 12:26:51
【问题描述】:

我在 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 并将对象查询到数据库,但我不想这样做,因为我会重复代码(在属性中查询用户)并且我需要使用我的应用程序中每个方法中的用户信息。

我希望我已经解释了自己,对不起我的英语不好

提前致谢:)

【问题讨论】:

  • 您还可以在对用户进行身份验证后将有关用户的附加信息存储为声明。可以在您的操作方法中访问当前经过身份验证的用户的声明。

标签: c# asp.net-mvc asp.net-web-api http-token-authentication


【解决方案1】:

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

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

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

GetType().GetCustomAttributes()

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

【讨论】:

  • 它返回空用户:/
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-01
  • 2010-09-28
  • 2014-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多