HtmlHelper 的 'ViewContext.Controller' 发生了什么?

What happened to HtmlHelper's 'ViewContext.Controller'?

在我的旧 ASP.NET 网络应用程序中,我编写了一个 HTML 帮助程序,通过访问 ViewContext.Controller:[=15= 来访问执行当前视图的控制器的上下文]

public static string GetControllerString(this HtmlHelper htmlHelper) {
    string controllerString = htmlHelper.ViewContext.Controller.ToString();
    return ".NET Controller: " + controllerString;
}

然而,ASP.NET Core 的 HTML 辅助对象中似乎不再存在:

public static string GetControllerString(this IHtmlHelper htmlHelper) {
    string controllerString = htmlHelper.ViewContext.Controller.ToString(); // Doesn't exist!
    return ".NET Core Controller: " + controllerString;
}

ViewContext.Controller 怎么了?现在是否无法从 HTML 辅助对象获取控制器上下文?

他们稍微改变了继承链和术语。因此,ASPNET Core 中的 ViewContext 不像旧的 ASPNET MVC framework.

那样继承自 ControllerContext

相反,ViewContext inherits 来自 ActionContext,这是更通用的术语。

因此,ViewContext 对象上没有继承 Controller 属性,而是可以使用 ActionDescriptor property,以获取所需的值。

public static string GetControllerString(this IHtmlHelper htmlHelper) {
    string actionDescriptor = htmlHelper.ViewContext.ActionDescriptor.DisplayName;
    return ".NET Core Controller: " + actionDescriptorName;
}