首页 > 解决方案 > ASP.NET Core:HtmlHelper 扩展(迁移问题)

问题描述

我正在尝试更新旧 MVC 项目(.NET Framework 4.5.2)中的一些代码以使用 .NET Core 2.2。我被困在 HtmlHelper 的扩展方法上,该方法在字符串中生成链接。

public static HtmlString GetMenu(this HtmlHelper htmlHelper)
{
   htmlString += string.Format("<li{0}>{1}</li>",
            controller == "Examples" ? " class=\"selected\"" : "",
            htmlHelper.ActionLink("Examples", "Index", "Examples")
        );
}

HtmlHelper 类位于 .NET Core 的 Microsoft.AspNetCore.Mvc.ViewFeatures 中,但 ActionLink 方法需要更多信息。它现在需要 8 个参数,而不是旧项目中的 3 个参数,其中两个是协议和主机名。但我不确定如何在不访问 HttpContext 的情况下在静态类中获取主机名和协议。

标签: c#html-helperasp.net-core-2.2

解决方案


在 ASP.NET Core 中,之前调用的类HtmlHelper现在已替换为 interface IHtmlHelper

这意味着所有链接扩展 ( HtmlHelperLinkExtensions) 也已切换到接口。

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.rendering.htmlhelperlinkextensions?view=aspnetcore-2.2


推荐阅读