EPiServer:获得带有语言标记的友好URL?

时间:2019-04-08 08:23:17

标签: c# episerver

我的变量langURL当前返回一个非友好的网址,例如:http://localhost:57299/link/457fee1669e348febf67ecb57b281945.aspx?epslanguage=de-AT

是否可以获取一个友好的网址?

public static IHtmlString HrefLangLinks(this PageData currentPage)
{

    var availablePageLanguages = currentPage.ExistingLanguages.Select(culture => culture.Name).ToArray();
    var Output = "";
    var langURL = "";

    foreach (string listitem in availablePageLanguages)
    {
        langURL = EPiServer.Web.UriUtil.AddLanguageSelection(currentPage.LinkURL, listitem);
        Output += "<link href=\"" + langURL + "\" hreflang=\"" + listitem + "\" rel=\"alternate\" >";
    }


    // Dictionary<String, String>
    return new HtmlString(Output.ToString());
}

对于每个页面,我也希望获得带有语言标记的友好网址,例如:

  • /
  • / de-DE
  • / zh-CN

2 个答案:

答案 0 :(得分:1)

是的,这是可能的。 试试这个:

public string GetExternalUrl(string linkUrl)
        {
            var result = string.Empty;
            try
            {
                var url = new UrlBuilder(linkUrl);
                Global.UrlRewriteProvider.ConvertToExternal(url, linkUrl, Encoding.UTF8);
                result = url.ToString();
            }
            catch (Exception)
            {
            }
            return result;
        }

答案 1 :(得分:0)

幸运的是,我们不再需要处理LinkURL属性。相反,我会使用UrlResolver

您的代码可以快速重写为如下形式:

public static IHtmlString HrefLangLinks(this PageData currentPage)
{
    // StringBuilder usually performs better than concatenating a variable number of strings.
    var sb = new StringBuilder;

    foreach (string language in currentPage.ExistingLanguages.Select(culture => culture.Name))
    {
        // Get the URL to the page in the individual languages, respecting the
        // website language settings (sometimes a language is bound to another hostname)
        string url = UrlResolver.Current.GetUrl(currentPage.ContentLink, language);
        sb.AppendLine($"<link href=\"{url}\" hreflang=\"{language}\" rel=\"alternate\"/>");
    }

    return new MvcHtmlString(sb.ToString());
}

但是我通常将这样的东西用作Razor助手。