在我过去用来测试各种项目的测试应用程序中,我有一个基本控制器。
基础控制器 (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);
}
}
Run Code Online (Sandbox Code Playgroud)
我现在正在为自己构建一个 Core 2.0 Web 模板,并试图在 Core 2.0 中实现基本控制器,但该方法出错了。
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);
}
Run Code Online (Sandbox Code Playgroud)
并且错误消息与被保护的方法有关
“BaseController.OnActionExecuted(ActionExecutedContext)”:覆盖“public”继承成员时无法更改访问修饰符
这在 MVC 5 中运行良好,现在使用 MVC 6 和 .Net Core 2,这是失败的。知道为什么在这种情况下不能保护或私有这种方法吗?我不明白为什么它需要公开。
此外,现在我正在重新查看这段代码,这是在每次调用控制器操作时检索用户,不是吗?必须有更好的方法来存储用户第一次登录时的信息。SqlDistributedCache?
基类中方法的访问修饰符Controller是public而不是protected:
public virtual void OnActionExecuted(ActionExecutedContext context);
Run Code Online (Sandbox Code Playgroud)
您也可以在此处的官方源代码中看到这一点。
编译器错误告诉您无法在继承的类中更改它。所以你只需要改变你的来匹配。