C#Url操作類封裝、仿Node.Js中的Url模塊實(shí)例
在實(shí)際開發(fā)中,需要用到的數(shù)據(jù)在url中,因此就需要我們來獲取到url中有用的信息,涉及到查詢、添加、修改、刪除等操作,下面我們就具體來了解一下。
1.簡單實(shí)例
目前常用Url操作,查詢、添加、修改、刪除鏈接參數(shù),重構(gòu)生成鏈接等功能。
//string url = "http://www.gongjuji.net:8081"; //string url = "http://www.gongjuji.net/"; //string url = "http://www.gongjuji.net/abc"; // string url = "http://www.gongjuji.net/abc/1234.html"; string url = "http://www.gongjuji.net/abc/1234.html?name=張三&age=1234#one#two"; //string url = "http://www.gongjuji.net/abc/1234.html?name=&age=#one#two"; //string url = "/abc/123.html?name=張三&age=1234#one#two"; // string url = "https://mp.weixin.qq.com/debug/cgi-bin/apiinfo?t=index&type=%E7%94%A8%E6%88%B7%E7%AE%A1%E7%90%86&form=%E8%8E%B7%E5%8F%96%E5%85%B3%E6%B3%A8%E8%80%85%E5%88%97%E8%A1%A8%E6%8E%A5%E5%8F%A3%20/user/get"; UrlAnalyze _url = new UrlAnalyze(url); JObject obj = JObject.FromObject(_url); Console.WriteLine(obj); //添加或修改參數(shù) _url.AddOrUpdateSearch("page", "2"); _url.AddOrUpdateSearch("name", "李四"); //重新生成鏈接參數(shù) Console.WriteLine(_url.GetUrl()); Console.WriteLine(_url.GetUrl(true));
2、實(shí)例:
識別字符串中的url
//string source = "工具集:http://www.gongjuji.net"; string source = @"工具集: http://www.gongjuji.net 愛漢字:http://hanzi.tianma3798.cn"; List<string> result = UrlAnalyze.GetUrlList(source); foreach (var item in result) { Console.WriteLine(item); } //替換成a標(biāo)簽 string result2 = UrlAnalyze.ReplaceToA(source); Console.WriteLine(result2);</string>
屬性和部分功能模仿了Node.js的url模塊
源代碼定義:
/// <summary> /// Url地址的格式化和反格式化 /// </summary> public class UrlAnalyze { /// <summary> /// 協(xié)議名稱 /// </summary> public string Protocol { get; set; } /// <summary> /// 是否以反斜杠結(jié)尾 /// </summary> public bool Slashes { get; set; } /// <summary> /// 驗(yàn)證信息,暫時(shí)不使用 /// </summary> public string Auth { get; set; } /// <summary> /// 全小寫主機(jī)部分,包括端口 /// </summary> public string Host { get { if (this.Port == null) return this.HostName; return string.Format("{0}:{1}", this.HostName, this.Port); } } /// <summary> /// 端口,為空時(shí)http默認(rèn)是80 /// </summary> public int? Port { get; set; } /// <summary> /// 小寫主機(jī)部分 /// </summary> public string HostName { get; set; } /// <summary> /// 頁面錨點(diǎn)參數(shù)部分 #one#two /// </summary> public string Hash { get; set; } /// <summary> /// 鏈接查詢參數(shù)部分(帶問號) ?one=1&two=2 /// </summary> public string Search { get; set; } /// <summary> /// 路徑部分 /// </summary> public string PathName { get; set; } /// <summary> /// 路徑+參數(shù)部分(沒有錨點(diǎn)) /// </summary> public string Path { get { if (string.IsNullOrEmpty(this.Search)) return this.PathName; return PathName + Search; } } /// <summary> /// 轉(zhuǎn)碼后的原鏈接 /// </summary> public string Href { get; set; } /// <summary> /// 參數(shù)的key=value 列表 /// </summary> private Dictionary<string, string=""> _SearchList = null; #region 初始化處理 /// <summary> /// 空初始化 /// </summary> public UrlAnalyze() { _SearchList = new Dictionary<string, string="">(); } /// <summary> /// 初始化處理 /// </summary> ///<param name="url">指定相對或絕對鏈接 public UrlAnalyze(string url) { //1.轉(zhuǎn)碼操作 this.Href = HttpUtility.UrlDecode(url); InitParse(this.Href); //是否反斜杠結(jié)尾 if (!string.IsNullOrEmpty(PathName)) this.Slashes = this.PathName.EndsWith("/"); //初始化參數(shù)列表 _SearchList = GetSearchList(); } /// <summary> /// 將字符串格式化成對象時(shí)初始化處理 /// </summary> private void InitParse(string url) { //判斷是否是指定協(xié)議的絕對路徑 if (url.Contains("://")) { // Regex reg = new Regex(@"(\w+):\/\/([^/:]+)(:\d*)?([^ ]*)"); Regex reg = new Regex(@"(\w+):\/\/([^/:]+)(:\d*)?(.*)"); Match match = reg.Match(url); //協(xié)議名稱 this.Protocol = match.Result("$1"); //主機(jī) this.HostName = match.Result("$2"); //端口 string port = match.Result("$3"); if (string.IsNullOrEmpty(port) == false) { port = port.Replace(":", ""); this.Port = Convert.ToInt32(port); } //路徑和查詢參數(shù) string path = match.Result("$4"); if (string.IsNullOrEmpty(path) == false) InitPath(path); } else { InitPath(url); } } /// <summary> /// 字符串url格式化時(shí),路徑和參數(shù)的初始化處理 /// </summary> ///<param name="path"> private void InitPath(string path) { Regex reg = new Regex(@"([^#?& ]*)(\??[^#]*)(#?[^?& ]*)"); Match match = reg.Match(path); //路徑和查詢參數(shù) this.PathName = match.Result("$1"); this.Search = match.Result("$2"); this.Hash = match.Result("$3"); } #endregion #region 參數(shù)處理 /// <summary> /// 獲取當(dāng)前參數(shù)解析結(jié)果字典列表 /// </summary> /// <returns></returns> public Dictionary<string, string=""> GetSearchList() { if (_SearchList != null) return _SearchList; _SearchList = new Dictionary<string, string="">(); if (!string.IsNullOrEmpty(Search)) { Regex reg = new Regex(@"(^|&)?(\w+)=([^&]*)", RegexOptions.Compiled); MatchCollection coll = reg.Matches(Search); foreach (Match item in coll) { string key = item.Result("$2").ToLower(); string value = item.Result("$3"); _SearchList.Add(key, value); } } return _SearchList; } /// <summary> /// 獲取查詢參數(shù)的值 /// </summary> ///<param name="key">鍵 /// <returns></returns> public string GetSearchValue(string key) { return _SearchList[key]; } /// <summary> /// 添加參數(shù)key=value,如果值已經(jīng)存在則修改 /// </summary> ///<param name="key">鍵 ///<param name="value">值 /// <returns></returns> public void AddOrUpdateSearch(string key, string value, bool Encode = false) { if (Encode) value = HttpUtility.UrlEncode(value); //判斷指定鍵值是否存在 if (_SearchList.ContainsKey(key)) { _SearchList[key] = value; } else { _SearchList.Add(key, value); } } /// <summary> /// 刪除指定key 的鍵值對 /// </summary> ///<param name="key">鍵 public void Remove(string key) { if (_SearchList.Any(q => q.Key == key)) _SearchList.Remove(key); } /// <summary> /// 獲取錨點(diǎn)列表 /// </summary> /// <returns></returns> public List<string> GetHashList() { List<string> list = new List<string>(); if (!string.IsNullOrEmpty(Hash)) { list = Hash.Split('#').Where(q => string.IsNullOrEmpty(q) == false) .ToList(); } return list; } #endregion /// <summary> /// 獲取最終url地址, /// 對參數(shù)值就行UrlEncode 編碼后,有可能和原鏈接不相同 /// </summary> /// <returns></returns> public string GetUrl(bool EncodeValue = false) { StringBuilder builder = new StringBuilder(); if (!string.IsNullOrEmpty(Protocol)) { //如果有協(xié)議 builder.Append(Protocol).Append("://"); } //如果有主機(jī)標(biāo)識 builder.Append(Host); //如果有目錄和參數(shù) if (!string.IsNullOrEmpty(PathName)) { string pathname = PathName; if (pathname.EndsWith("/")) pathname = pathname.Substring(0, pathname.Length - 1); builder.Append(pathname); } //判斷是否反斜杠 if (Slashes) { builder.Append("/"); } Dictionary<string, string=""> searchList = GetSearchList(); if (searchList != null && searchList.Count > 0) { builder.Append("?"); bool isFirst = true; foreach (var item in searchList) { if (isFirst == false) { builder.Append("&"); } isFirst = false; builder.AppendFormat("{0}={1}", item.Key, EncodeValue ? HttpUtility.UrlEncode(item.Value) : item.Value); } } //錨點(diǎn) builder.Append(Hash); return builder.ToString(); } #region 靜態(tài)方法 /// <summary> /// 獲取源字符串中所有的鏈接(可能有重復(fù)) /// </summary> ///<param name="content">源字符串 /// <returns></returns> public static List<string> GetUrlList(string content) { List<string> list = new List<string>(); Regex re = new Regex(@"(?<url>http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?)"); MatchCollection mc = re.Matches(content); foreach (Match m in mc) { if (m.Success) { string url = m.Result("${url}"); list.Add(url); } } return list; } /// <summary> /// 將字符串中的鏈接成標(biāo)簽 /// </summary> ///<param name="content"> /// <returns></returns> public static string ReplaceToA(string content) { Regex re = new Regex(@"(?<url>http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?)"); MatchCollection mc = re.Matches(content); foreach (Match m in mc) { content = content.Replace(m.Result("${url}"), String.Format("</url>{0}", m.Result("${url}"))); } return content; } #endregion }</url></string></string></string></string,></string></string></string></string,></string,></string,></string,>
所屬源代碼庫:https://github.com/tianma3798/Common
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
C#數(shù)據(jù)類型轉(zhuǎn)換(顯式轉(zhuǎn)型、隱式轉(zhuǎn)型、強(qiáng)制轉(zhuǎn)型)
本文詳細(xì)講解了C#數(shù)據(jù)類型轉(zhuǎn)換(顯式轉(zhuǎn)型、隱式轉(zhuǎn)型、強(qiáng)制轉(zhuǎn)型),文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-01-01C#創(chuàng)建自定義控件及添加自定義屬性和事件使用實(shí)例詳解
這篇文章主要給大家介紹了關(guān)于C#創(chuàng)建自定義控件及添加自定義屬性和事件使用的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用C#具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05unity自帶尋路(導(dǎo)航)系統(tǒng) Nav Mesh導(dǎo)航網(wǎng)格
這篇文章主要為大家詳細(xì)介紹了unity自帶尋路(導(dǎo)航)系統(tǒng),Nav Mesh導(dǎo)航網(wǎng)格,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11C#實(shí)現(xiàn)HTML和UBB互相轉(zhuǎn)換的方法
這篇文章主要介紹了C#實(shí)現(xiàn)HTML和UBB互相轉(zhuǎn)換的方法,通過兩個(gè)自定義函數(shù)DoHtmlToUB與ubbtohtml來實(shí)現(xiàn)HTML代碼與ubb代碼間的相互轉(zhuǎn)換,是非常實(shí)用的技巧,需要的朋友可以參考下2014-11-11C# winform編程中響應(yīng)回車鍵的實(shí)現(xiàn)代碼
這篇文章主要介紹了C# winform編程中響應(yīng)回車鍵的實(shí)現(xiàn)代碼,既在窗口上響應(yīng)回車鍵事件的方法,需要的朋友可以參考下2014-08-08C#實(shí)現(xiàn)將CSV轉(zhuǎn)為XLSX文件
Microsoft?Excel的XLSX格式以及基于文本的CSV(逗號分隔值)格式,是數(shù)據(jù)交換中常見的文件格式,本文主要介紹了如何在C#中以編程的方式將CSV文件轉(zhuǎn)化為XLSX?文件,需要的可以參考下2024-03-03C#使用時(shí)序數(shù)據(jù)庫InfluxDB的教程詳解
InfluxDB是一個(gè)開源的時(shí)序數(shù)據(jù)庫,可以自動(dòng)處理時(shí)間序列數(shù)據(jù),這篇文章主要為大家詳細(xì)介紹了C#如何使用InfluxDB,感興趣的小伙伴可以跟隨小編一起了解下2023-11-11