簡體   English   中英

如何從 URL 檢索區域設置(國家/地區)代碼?

[英]How to retrieve the locale(country) code from URL?

我有一個 URL,類似於http://example.com/UK/Deal.aspx?id=322

我的目標是刪除語言環境(國家/地區)部分,使其像http://example.com/Deal.aspx?id=322

由於 URL 可能有其他類似的格式,例如: https://ssl.example.com/JP/Deal.aspx?id=735 ,使用“子字符串”函數不是一個好主意。

我能想到的就是用下面的方法把它們分開,然后再映射回去。

HttpContext.Current.Request.Url.Scheme
HttpContext.Current.Request.Url.Host
HttpContext.Current.Request.Url.AbsolutePath
HttpContext.Current.Request.Url.Query

並且,假設HttpContext.Current.Request.Url.AbsolutePath將是:

/UK/Deal.aspx?id=322  

我不知道如何處理這個,因為我的老板讓我不要使用“正則表達式”(他認為這會影響性能......)

除了正則表達式”,還有其他方法可以從中刪除UK嗎?

ps:英國部分可能是JPDE或其他國家/地區代碼。

順便說一句,對於美國,沒有國家代碼,網址將是http://example.com/Deal.aspx?id=322

也請考慮這種情況。 謝謝你。

假設您將在 Url 中有TwoLetterCountryISOName y您可以使用UriBuilder類從Uri刪除路徑,而無需使用Regex

例如

    var originalUri = new Uri("http://example.com/UK/Deal.aspx?id=322");
    if (IsLocaleEnabled(sourceUri))
       {
         var builder = new UriBuilder(sourceUri);
         builder.Path 
          = builder.Path.Replace(sourceUri.Segments[1] /* remove UK/ */, string.Empty);
          // Construct the Uri with new path
          Uri newUri = builder.Uri;;
       }

更新:

// Cache the instance for performance benefits.
static readonly Regex regex = new Regex(@"^[aA-zZ]{2}\/$", RegexOptions.Compiled);

/// <summary>
/// Regex to check if Url segments have the 2 letter 
/// ISO code as first ocurrance after root
/// </summary>
private bool IsLocaleEnabled(Uri sourceUri)
{
  // Update: Compiled regex are way much faster than using non-compiled regex.
  return regex.IsMatch(sourceUri.Segments[1]);
}

為了性能優勢,您必須緩存它(意味着將其保存在靜態只讀字段中) 無需為每個請求解析預定義的正則表達式。 通過這種方式,您將獲得可以獲得的所有性能優勢。

結果 - http://example.com/Deal.aspx?id=322

這完全取決於國家代碼是否始終具有相同的位置。 如果不是,則需要有關可能格式的更多詳細信息。也許您可以檢查第一段是否有兩個字符或其他內容,以確保它確實是國家/地區代碼(但不確定這是否可靠)。 或者您從文件名開始,如果它總是采用/[optionalCountryCode]/deal.aspx?...格式/[optionalCountryCode]/deal.aspx?...

這兩種方法如何(在字符串級別):

public string RemoveCountryCode()
{
  Uri originalUri = new Uri("http://example.com/UK/Deal.aspx?id=322");
  string hostAndPort = originalUri.GetLeftPart(UriPartial.Authority);

  // v1: if country code is always there, always has same position and always
  // has format 'XX' this is definitely the easiest and fastest
  string trimmedPathAndQuery = originalUri.PathAndQuery.Substring("/XX/".Length);

  // v2: if country code is always there, always has same position but might
  // not have a fixed format (e.g. XXX)
  trimmedPathAndQuery = string.Join("/", originalUri.PathAndQuery.Split('/').Skip(2));

  // in both cases you need to join it with the authority again
  return string.Format("{0}/{1}", hostAndPort, trimmedPathAndQuery);
}

如果 AbsolutePath 總是采用/XX/...pagename.aspx?id=###格式,其中XX是兩個字母的國家/地區代碼,那么您可以/XX/...pagename.aspx?id=###前 3 個字符。

刪除前 3 個字符的示例:

var targetURL = HttpContext.Current.Request.Url.AbsolutePath.Substring(3);

如果國家/地區代碼的長度可能不同,那么您可以找到第二個/字符的索引並從那里開始子字符串。

var sourceURL = HttpContext.Current.Request.Url.AbsolutePath;
var firstOccurance = sourceURL.IndexOf('/')
var secondOccurance = sourceURL.IndexOf('/', firstOccurance);

var targetURL = sourceURL.Substring(secondOccurance);

簡單的方法是將其視為字符串,用“/”分隔符分割它,刪除第四個元素,然后再次用“/”分隔符將它們連接起來:

    string myURL = "https://ssl.example.com/JP/Deal.aspx?id=735";
    List<string> myURLsplit = myURL.Split('/').ToList().RemoveAt(3);
    myURL = string.Join("/", myURLsplit);

RESULT: https://ssl.example.com/Deal.aspx?id=735

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM