Let's say we have code which retrieves a list of items from a database. The resulting list depends on the user permissions. What I want is to make this code reusable, i.e. callable from multiple controllers. What is the standard way of doing this?
For authentification in my code I load a User from the database via
User user = dbContext.User.SingleOrDefault(x => x.access_token == User.Identity.Name);
This is the authentification schmeme I'm using in Startup.cs:
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
}).AddCookie("Cookies", options =>
{
options.Cookie.Name = "auth_cookie";
options.Cookie.SameSite = SameSiteMode.None;
options.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = redirectContext =>
{
redirectContext.HttpContext.Response.StatusCode = 401;
return Task.CompletedTask;
}
};
});
I tried to put the code retrieving the list directly in one controller and for the other controllers which need the code to call that controller via
services.AddControllersAsServices()
and then
(MyController)HttpContext.RequestServices.GetService(typeof(MyController));
but the User property from ControllerBase was null.
I have read all of the documentation I could find but could not find a solution that the User or HttpContext properties have a value.