In a test app I had been using to test various items in the past, I had a base controller.
BaseController (MVC5)
public abstract class BaseController : Controller
{
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (User != null)
{
var context = new ApplicationDbContext();
var username = User.Identity.Name;
var iconSource = ServicesAppSettings.UserIcons.FemaleUserIconSource;
if (!string.IsNullOrEmpty(username))
{
var user = context.Users.SingleOrDefault(u => u.UserName == username);
if (user != null)
{
var gender = user.GetUserGender(username);
if (gender == DomainClasses.Enums.Gender.Male)
{
iconSource = ServicesAppSettings.UserIcons.MaleUserIconSource;
}
var fullName = user.GetFullName(username);
ViewData.Add("FullName", fullName);
ViewData.Add("IconSource", iconSource);
}
}
}
base.OnActionExecuted(filterContext);
}
}
I am now building a Core 2.0 web template for myself and was trying to implement the base controller in Core 2.0 but the method is erring.
BaseController(MVC 6, .Net core 2.0)
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (User != null)
{
var baseArgs = new[] { "TestApp" };
var context = ApplicationDbContextFactory.CreateDbContext(baseArgs);
var username = User.Identity.Name;
var iconSource = _config.GetSection("FemaleUserIcon");
if (!string.IsNullOrEmpty(username))
{
var user = context.Users.SingleOrDefault(u => u.UserName == username);
if (user != null)
{
var gender = user.GetUserGender(username);
if (gender == Gender.Male)
{
iconSource = _config.GetSection("MaleUserIcon");
}
var fullName = user.GetFullName(username);
ViewData.Add("FullName", fullName);
ViewData.Add("IconSource", iconSource);
}
}
}
base.OnActionExecuted(filterContext);
}
And the error message has to do with the method being protected
'BaseController.OnActionExecuted(ActionExecutedContext)': cannot change access modifiers when overriding 'public' inherited member
This worked perfectly fine in MVC 5, now using MVC 6 and .Net Core 2, this is failing. Any idea why this method can't be protected or private in this scenario? I don't see why it needs to be public.
Additionally, now that I am re-looking at this code, this is retrieving the user every time a controller action is called, isn't it? There has to be a better way to store this info the first time a user logs in. SqlDistributedCache?