从方法访问属性数据
Access Attribute data from method
我正在使用 asp.net 核心 api 项目,我使用自定义 ActionFilter 属性进行一些身份验证验证,如下所示:
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();
}
}
}
然后我将这个属性放在 api 控制器中的一个动作上,如下所示:
[HttpGet("user/GetAccountInfo")]
[LoggedIn]
public AccountInfoDTO GetAccountInfo()
{
//Here i want to get the placed [LoggedIn] instance to get it's LoggedInUser value
}
我需要在方法中获取 LoggedInUser 属性,我尝试了一些反射,但每次都得到 null。
根据您的描述,我们无法直接读取控制器操作中的 LoggedInAttribute 属性,它们是不同的 class。
如果想获取登录模型,建议放在httpcontext项中,在action中读取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();
}
结果:
我正在使用 asp.net 核心 api 项目,我使用自定义 ActionFilter 属性进行一些身份验证验证,如下所示:
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();
}
}
}
然后我将这个属性放在 api 控制器中的一个动作上,如下所示:
[HttpGet("user/GetAccountInfo")]
[LoggedIn]
public AccountInfoDTO GetAccountInfo()
{
//Here i want to get the placed [LoggedIn] instance to get it's LoggedInUser value
}
我需要在方法中获取 LoggedInUser 属性,我尝试了一些反射,但每次都得到 null。
根据您的描述,我们无法直接读取控制器操作中的 LoggedInAttribute 属性,它们是不同的 class。
如果想获取登录模型,建议放在httpcontext项中,在action中读取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();
}
结果: