c# - 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.
解决方案
根据您的描述,我们无法直接读取控制器操作中的 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();
}
结果:
推荐阅读
- php - 在 WHM/Cpanel 上使用 PDO 连接到 SQL Server
- python - /bin/sh python 在运行 docker 基础映像时未找到错误
- excel - VBA 超链接到选项卡
- python - PyInstaller 生成的 Exe 在另一台机器上悄然失败
- python-3.x - Python (discord.py) 如何识别发送的消息是嵌入消息还是普通文本?
- python - 根据值的条件对数据框中的列重新排序
- unit-testing - 未解决的参考:TestCoroutineDispatcher
- python - 我怎样才能优化这个多数票
- configuration - autofac 配置文件启用拦截器
- javascript - 扩展运算符在导入的模块中不起作用。但是在我自己的代码中工作