Reputation: 3032
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.
Upvotes: 0
Views: 193
Reputation: 28257
According to your description, we couldn't directly read the LoggedInAttribute property in the controller action, they are different class.
If you want to get the login model, I suggest you could put it in httpcontext item and read the httpcontext item in the action.
More details, you could refer to below codes:
public void OnActionExecuting(ActionExecutingContext context)
{
LoggedInUser = new Login { Id = 1 };
context.HttpContext.Items["Login"] = LoggedInUser;
//throw new NotImplementedException();
}
Action:
[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();
}
Result:
Upvotes: 1