[ASP.NET MVC] 取得 Request 常用資訊 (IP, 作業系統, 瀏覽器, 呼叫網址)
在建置網頁的時候,有時候會需要知道來源端它的環境是什麼,可能是需要記錄來源的 IP,或是依照來源的作業系統而顯示對應的畫面。
在 ASP.Net MVC 裡面想要知道來源端的資訊,全部都放在 Request 這個物件裡面。
接下來我就展示 Request 內常用的資訊,如果想了解 Request 內的資訊,我在後面也放上完整取得 Rquest 內的資訊。
Contents
Request 常用資訊
常用資訊裡面我列出了 5 個項目,分別是來源 IP, 作業系統, 瀏覽器, 呼叫網址等資訊。
看看執行的畫面
程式碼
1 2 3 4 5 6 7 8 9 |
StringBuilder sbMsg = new StringBuilder(); sbMsg.Append("來源IP: " + this.GetClientIP() + "<br>"); sbMsg.Append("來源系統: " + this.GetUserPlatform() + "<br>"); sbMsg.Append("來源瀏覽器: " + this.GetClientBrowserVersion() + "<br>"); sbMsg.Append("來源相對網址: " + Request.CurrentExecutionFilePath + "<br>"); sbMsg.Append("來源絕對網址: " + Request.Url.AbsoluteUri + "<br>"); ViewData["sbMsg"] = sbMsg.ToString(); |
方法程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 |
/// <summary> /// 來源 IP /// </summary> /// <returns></returns> public string GetClientIP() { string ClientIP = ""; if (Request.ServerVariables["HTTP_VIA"] == null) { ClientIP = Request.ServerVariables["REMOTE_ADDR"].ToString(); } else { ClientIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); } ClientIP = ClientIP.Replace("::1", "127.0.0.1"); return ClientIP; } /// <summary> /// 取得使用者系統 /// </summary> /// <param name="request"></param> /// <returns></returns> public String GetUserPlatform() { var ua = Request.UserAgent; if (ua.Contains("Android")) return string.Format("Android {0}", GetMobileVersion(ua, "Android")); if (ua.Contains("iPad")) return string.Format("iPad OS {0}", GetMobileVersion(ua, "OS")); if (ua.Contains("iPhone")) return string.Format("iPhone OS {0}", GetMobileVersion(ua, "OS")); if (ua.Contains("Linux") && ua.Contains("KFAPWI")) return "Kindle Fire"; if (ua.Contains("RIM Tablet") || (ua.Contains("BB") && ua.Contains("Mobile"))) return "Black Berry"; if (ua.Contains("Windows Phone")) return string.Format("Windows Phone {0}", GetMobileVersion(ua, "Windows Phone")); if (ua.Contains("Mac OS")) return "Mac OS"; if (ua.Contains("Windows NT 5.1") || ua.Contains("Windows NT 5.2")) return "Windows XP"; if (ua.Contains("Windows NT 6.0")) return "Windows Vista"; if (ua.Contains("Windows NT 6.1")) return "Windows 7"; if (ua.Contains("Windows NT 6.2")) return "Windows 8"; if (ua.Contains("Windows NT 6.3")) return "Windows 8.1"; if (ua.Contains("Windows NT 10")) return "Windows 10"; //fallback to basic platform: return Request.Browser.Platform + (ua.Contains("Mobile") ? " Mobile " : ""); } /// <summary> /// 取得遠端呼叫者瀏覽器版本 /// </summary> /// <returns></returns> public string GetClientBrowserVersion() { HttpBrowserCapabilitiesBase bc = Request.Browser; string brow_ver = bc.Browser + " " + bc.Version; return brow_ver; } /// <summary> /// 取得手機版本 /// </summary> /// <param name="userAgent"></param> /// <param name="device"></param> /// <returns></returns> public String GetMobileVersion(string userAgent, string device) { var temp = userAgent.Substring(userAgent.IndexOf(device) + device.Length).TrimStart(); var version = string.Empty; foreach (var character in temp) { var validCharacter = false; int test = 0; if (Int32.TryParse(character.ToString(), out test)) { version += character; validCharacter = true; } if (character == '.' || character == '_') { version += '.'; validCharacter = true; } if (validCharacter == false) break; } return version; } |
列出所有 Request 資訊
如果想要完整了解 Request 內所有的資訊,可以用此語法查看
1 2 3 4 5 6 7 8 9 10 |
StringBuilder sbRequest = new StringBuilder(); for (int i = 0; i < Request.Headers.Count; i++) { sbRequest.AppendLine(Request.Headers.GetKey(i).ToString() + "=" + Request.Headers[i] + "<br>"); } for (int i = 0; i < Request.ServerVariables.Count; i++) { sbRequest.AppendLine(Request.ServerVariables.GetKey(i).ToString() + "=" + Request.ServerVariables[i] + "<br>"); } ViewData["sbRequest"] = sbRequest.ToString(); |
執行後呈現的畫面
顯示的資訊太多,後面就拍不到了,大家可以自己試試看喔。
相關學習文章
- [C#] Base64 Convert.ToBase64String 基本轉碼及適用網址參數轉碼延伸應用
- ASP.NET MVC 的 Razor 語法如何顯示關鍵字符號 @
- [ASP.NET MVC] 前台會員註冊範例教學 #CH1 (附範例下載)
如果你在學習上有不懂的地方,需要諮詢服務,可以參考站長服務,我想辨法解決你的問題
如果文章內容有過時、不適用或錯誤的地方,幫我在下方留言通知我一下,謝謝
為什麼我會抓到自己內網的IP 而不是訪客的真實IP呢?
你是不是連自己的內網呢?是的話就會出現內網IP喔
如果是訪客身份去連別人的網站,才會出現訪客的 IP
我是從家裡的手機網路 和 家裡的網路 連網站 抓到的都是內網 IP 讓我覺得納悶
我這裡提供其他取 ip 的方法給你參考
///
///
/// GetHostIPAddress() lstIPAddress = new List ();
public static List
{
List
IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ipa in IpEntry.AddressList)
{
if (ipa.AddressFamily == AddressFamily.InterNetwork)
lstIPAddress.Add(ipa.ToString());
}
return lstIPAddress;
}
///
///
///
public string GetClientIP()
{
string ClientIP = "";
if (Request.ServerVariables["HTTP_VIA"] == null)
{
ClientIP = Request.ServerVariables["REMOTE_ADDR"].ToString();
}
else
{
ClientIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
ClientIP = ClientIP.Replace("::1", "127.0.0.1");
return ClientIP;
}
///
///
///
public static string GetExtranetIPAddress()
{
HttpWebRequest request = HttpWebRequest.Create("http://www.whatismyip.com.tw") as HttpWebRequest;
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0";
string ip = string.Empty;
WebResponse response = request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string result = reader.ReadToEnd();
string pattern = @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}";
ip = Regex.Match(result, pattern).ToString();
}
return ip;
}
跑 GetExtranetIPAddress() 裡面的 WebResponse response = request.GetResponse(); 會出現 基礎連接已關閉: 連接意外關閉
太久沒連了,對方已經不支援這樣取了
我提供另外取得對外ip的方法
///
///
///
public static string GetExtranetIPAddress()
{
HttpWebRequest request = HttpWebRequest.Create(“http://ipinfo.io/ip”) as HttpWebRequest;
request.Method = “GET”;
request.ContentType = “application/x-www-form-urlencoded”;
request.UserAgent = “Mozilla/5.0″;
string ip = string.Empty;
WebResponse response = request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string result = reader.ReadToEnd();
string pattern = @”\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}”;
ip = Regex.Match(result, pattern).ToString();
}
return ip;
}