C#Url操作類封裝、仿Node.Js中的Url模塊實例
在實際開發(fā)中,需要用到的數(shù)據(jù)在url中,因此就需要我們來獲取到url中有用的信息,涉及到查詢、添加、修改、刪除等操作,下面我們就具體來了解一下。
1.簡單實例
目前常用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、實例:
識別字符串中的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標簽
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>
/// 驗證信息,暫時不使用
/// </summary>
public string Auth { get; set; }
/// <summary>
/// 全小寫主機部分,包括端口
/// </summary>
public string Host
{
get
{
if (this.Port == null)
return this.HostName;
return string.Format("{0}:{1}", this.HostName, this.Port);
}
}
/// <summary>
/// 端口,為空時http默認是80
/// </summary>
public int? Port { get; set; }
/// <summary>
/// 小寫主機部分
/// </summary>
public string HostName { get; set; }
/// <summary>
/// 頁面錨點參數(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ù)部分(沒有錨點)
/// </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>
/// 將字符串格式化成對象時初始化處理
/// </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");
//主機
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ù)的初始化處理
/// </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>
/// 獲取當前參數(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>
/// 獲取錨點列表
/// </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("://");
}
//如果有主機標識
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);
}
}
//錨點
builder.Append(Hash);
return builder.ToString();
}
#region 靜態(tài)方法
/// <summary>
/// 獲取源字符串中所有的鏈接(可能有重復)
/// </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>
/// 將字符串中的鏈接成標簽
/// </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
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
您可能感興趣的文章
- 01-10C#實現(xiàn)讀取注冊表監(jiān)控當前操作系統(tǒng)已安裝軟件變化的方法
- 01-10C#實現(xiàn)實體類與字符串互相轉(zhuǎn)換的方法
- 01-10C#實現(xiàn)判斷當前操作用戶管理角色的方法
- 01-10C#通過Semaphore類控制線程隊列的方法
- 01-10C#3.0使用EventLog類寫Windows事件日志的方法
- 01-10C#中DataGridView常用操作實例小結(jié)
- 01-10C#操作ftp類完整實例
- 01-10asp.net中XML如何做增刪改查操作
- 01-10winform簡單緩存類實例
- 01-10C#實現(xiàn)控制攝像頭的類


閱讀排行
本欄相關(guān)
- 01-10C#通過反射獲取當前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實現(xiàn)txt定位指定行完整實例
- 01-10WinForm實現(xiàn)仿視頻播放器左下角滾動新
- 01-10C#停止線程的方法
- 01-10C#實現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實現(xiàn)讀取注冊表監(jiān)控當前操作系統(tǒng)已
隨機閱讀
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 08-05織夢dedecms什么時候用欄目交叉功能?
- 01-10C#中split用法實例總結(jié)
- 01-10delphi制作wav文件的方法
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 01-11ajax實現(xiàn)頁面的局部加載
- 04-02jquery與jsp,用jquery
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改


