首页 > 解决方案 > Access Attribute data from method

问题描述

I'm using asp.net core api project and I use a custom ActionFilter attribute to do some authentication validations as below:

public class LoggedInAttribute : ActionFilterAttribute
{
    public Login LoggedInUser { get; private set; }
    public override void OnActionExecuting(ActionExecutingContext con)
    {
        LoggedInUser = //here i get the logged in user(from a http token request header) and load it from database
        if (LoggedInUser == null)
        {
            con.Result = new UnauthorizedResult();
        }
    }
}

Then I placed this attribute on an action in the api controller as below:

    [HttpGet("user/GetAccountInfo")]
    [LoggedIn]
    public AccountInfoDTO GetAccountInfo()
    {
       //Here i want to get the placed [LoggedIn] instance to get it's LoggedInUser value
    }

I need to get the LoggedInUser property inside the method, I've tried some reflection but I get null everytime.

标签: c#asp.net-coreasp.net-web-apireflectionattributes

解决方案


根据您的描述,我们无法直接读取控制器操作中的 LoggedInAttribute 属性,它们是不同的类。

如果你想得到登录模型,我建议你可以把它放在 httpcontext 项中,并阅读动作中的 httpcontext 项。

更多细节,您可以参考以下代码:

    public void OnActionExecuting(ActionExecutingContext context)
    {
        LoggedInUser = new Login { Id = 1 };

        context.HttpContext.Items["Login"] = LoggedInUser;
        
        //throw new NotImplementedException();
    }

行动:

  [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        var loginuser = HttpContext.Items["Login"];
        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }

结果:

在此处输入图像描述


推荐阅读