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

标签 c# asp.net asp.net-core .net-core html-helper

在我的旧 ASP.NET 网络应用程序中,我编写了一个 HTML 帮助程序,以通过访问 ViewContext.Controller 来访问执行当前 View 的 Controller 的上下文:

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 帮助器对象获取 Controller 上下文吗?

最佳答案

他们稍微改变了继承链和术语。因此,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;
}

关于c# - HtmlHelper 的 'ViewContext.Controller' 发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57725757/

相关文章:

c# - 如何在 C# 中使用 Bouncy CaSTLe 将 X.509 v.3 谷歌证书添加到项目中

c# - 哪个命名空间在 CaSTLe Windsor 中拥有 Component.For?

c# - 从 Html Agility Pack HtmlWeb 获取 HttpWebResponse

c# - 找不到与命令 "dotnet-/app/Build\ClearPluginAssemblies.dll"Docker 匹配的可执行文件

c# - 如何使用?或者 ??有条件地呈现 Blazor 模板?

c# - 创建类

c# - Thread.CurrentPrincipal 错误地声称是匿名的

asp.net - 注册外部登录时 CreateUserAsync 失败

asp.net - 如何在不同选项卡中设置默认按钮?

c# - 获取 IHostingServices 实例的正确方法