2010-09-10 34 views
1

我的代碼:ASP.NET初學者問題:使用一些類庫方面需要幫助

protected void Page_Load(object sender, EventArgs e) 
    { 
     String userHost = Request.UserHostName 
    } 

這是獲取IP地址好了,但現在我想知道訪問者的國家,使用國名相應地將訪問者重定向到某個網頁。

我遇到了這個庫,但沒有線索如何在項目中使用它。其實我有,但我不確定,所以我問。

http://ipaddressextensions.codeplex.com/

當我從該ZIP文件夾上面下載了一個DLL文件和XML文件。現在,我該怎麼處理這兩個問題?像包含在項目中。那麼我在代碼文件中輸入什麼?

類似於以下內容。

if (countryName=="France") 
{ 
    response.redirect("www.mysite.fr") 
} 
else 
    if(countryName=="India") 
    { 
     response.redirect("www.mysite.in") 
    } 

等等...

我怎麼做呢?我真的需要爲所有國家輸入很多if塊。我如何縮短這段代碼?

回答

3

縮短您的代碼將所有國家放在字典中。

Dictionary<string,string> dict; 

public void Init(){ 
    dict = new Dictionary<string,string>(); 
    dict["India"] = "www.mysite.in"; 
    dict["France"] = "www.mysite.fr"; 
} 

public string GetPage(string country){ 
    string result = dict["Default"]; 

    if(dict.ContainsKey(theKey)){ 
     result = dict[theKey]; 
    } 
    return result; 
} 

只需添加引用,然後在「使用說明」和API是你的使用。

你甚至可以改變上面的IP地址。

首先添加參考和以下using到您的代碼。

using WorldDomination.Net; 

public string GetPage(string ipAddress){ 
    string result = null; 
    IPAddress ipAddress; 
    if (IPAddress.TryParse(userHostIpAddress, out ipAddress)) 
    { 
     string fullNameKey= ipAddress.Country(); 
     //Or you could use two letter code 
     //string twoLetterKey = ipAddress.Iso3166TwoLetterCode(); 
     if(dict.ContainsKey(theKey)){ 
      result = dict[fullNameKey]; 
     } 
    } 
    else 
    { 
     result = dict["Default"]; 
    } 
    return result; 
} 
+0

並縮短它甚至更多的使用初始化語法。新字典 {{contry1,url1},...,{countryn,urln}}; – 2010-09-10 13:06:24

1

您需要將對下載庫(dll)的引用添加到您的項目中。有關添加參考的詳細信息,請參見http://msdn.microsoft.com/en-us/library/7314433t%28v=VS.90%29.aspx

「你在代碼文件中輸入的內容」將完全取決於庫本身。如果您不確定如何實現庫的功能,我建議您查看CodePlex頁面上託管的source code repository中包含的測試項目。它應該顯示你需要調用什麼方法。幸運的是,類和方法結構是不言自明的。

如果您不想使用if() { } else if() { }塊,您可以選擇使用switch statement來代替。

switch(countryName) { 
    case "India": 
     // do something 
     break; 
    case "France": 
     // do something 
     break; 
    case "Japan": 
     // do something 
     break; 
    case "Germany": 
     // do something 
     break; 
    default: 
     // do something 
     break; 
} 
+0

確定添加了dll ..這是什麼xml的?我是否也需要在項目中包含這些內容? – Serenity 2010-09-10 11:52:58

+0

也...那個dll文件存儲在我的桌面..如果我在我的項目中添加引用,然後從桌面上刪除dll ..它會給錯誤說dll丟失? – Serenity 2010-09-10 11:56:05

+1

@happysoul XML文件包含庫文檔。您不需要引用XML本身,但是如果將它保存在與DLL相同的文件夾中,IntelliSense將爲您提供該文檔。 – 2010-09-10 11:56:19

0

http://ipaddressextensions.codeplex.com/網站給出了查找國家的示例代碼。一旦你找到了國家,然後根據國家將它與你的子域進行比較,然後重定向它。 `使用System.Net;使用WorldDomination.Net的 ;

string userHostIpAddress = "203.1.2.3"; 
IPAddress ipAddress; 
if (IPAddress.TryParse(userHostIpAddress, out ipAddress)) 
    { 
    string country = ipAddress.Country(); // return value: UNITED STATES 
    string iso3166TwoLetterCode = ipAddress.Iso3166TwoLetterCode(); //return value: US 
    } `