C#Url操作類封裝、仿Node.Js中的Url模塊實例。本站提示廣大學習愛好者:(C#Url操作類封裝、仿Node.Js中的Url模塊實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#Url操作類封裝、仿Node.Js中的Url模塊實例正文
在現實開辟中,須要用到的數據在url中,是以就須要我們來獲得到url中有效的信息,觸及到查詢、添加、修正、刪除等操作,上面我們就詳細來懂得一下。
1.簡略實例
今朝經常使用Url操作,查詢、添加、修正、刪除鏈接參數,重構生成鏈接等功效。
//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);
//添加或修正參數
_url.AddOrUpdateSearch("page", "2");
_url.AddOrUpdateSearch("name", "李四");
//從新生成鏈接參數
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.WordStrToA(source);
Console.WriteLine(result2);</string>

屬性和部門功效模擬了Node.js的url模塊
源代碼界說:
/// <summary>
/// Url地址的格局化和反格局化
/// </summary>
public class UrlAnalyze
{
/// <summary>
/// 協定稱號
/// </summary>
public string Protocol { get; set; }
/// <summary>
/// 能否以反斜槓開頭
/// </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>
/// 頁面錨點參數部門 #one#two
/// </summary>
public string Hash { get; set; }
/// <summary>
/// 鏈接查詢參數部門(帶問號) ?one=1&two=2
/// </summary>
public string Search { get; set; }
/// <summary>
/// 途徑部門
/// </summary>
public string PathName { get; set; }
/// <summary>
/// 途徑+參數部門(沒有錨點)
/// </summary>
public string Path
{
get
{
if (string.IsNullOrEmpty(this.Search))
return this.PathName;
return PathName + Search;
}
}
/// <summary>
/// 轉碼後的原鏈接
/// </summary>
public string Href { get; set; }
/// <summary>
/// 參數的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.轉碼操作
this.Href = HttpUtility.UrlDecode(url);
InitParse(this.Href);
//能否反斜槓開頭
if (!string.IsNullOrEmpty(PathName))
this.Slashes = this.PathName.EndsWith("/");
//初始化參數列表
_SearchList = GetSearchList();
}
/// <summary>
/// 將字符串格局化成對象時初始化處置
/// </summary>
private void InitParse(string url)
{
//斷定能否是指定協定的相對途徑
if (url.Contains("://"))
{
// Regex reg = new Regex(@"(\w+):\/\/([^/:]+)(:\d*)?([^ ]*)");
Regex reg = new Regex(@"(\w+):\/\/([^/:]+)(:\d*)?(.*)");
Match match = reg.Match(url);
//協定稱號
this.Protocol = match.Result("$1");
//主機
this.HostName = match.Result("$2");
//端口
string port = match.Result("$3");
if (string.IsNullOrEmpty(port) == false)
{
port = port.WordStr(":", "");
this.Port = Convert.ToInt32(port);
}
//途徑和查詢參數
string path = match.Result("$4");
if (string.IsNullOrEmpty(path) == false)
InitPath(path);
}
else
{
InitPath(url);
}
}
/// <summary>
/// 字符串url格局化時,途徑和參數的初始化處置
/// </summary>
///<param name="path">
private void InitPath(string path)
{
Regex reg = new Regex(@"([^#?& ]*)(\??[^#]*)(#?[^?& ]*)");
Match match = reg.Match(path);
//途徑和查詢參數
this.PathName = match.Result("$1");
this.Search = match.Result("$2");
this.Hash = match.Result("$3");
}
#endregion
#region 參數處置
/// <summary>
/// 獲得以後參數解析成果字典列表
/// </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>
/// 獲得查詢參數的值
/// </summary>
///<param name="key">鍵
/// <returns></returns>
public string GetSearchValue(string key)
{
return _SearchList[key];
}
/// <summary>
/// 添加參數key=value,假如值曾經存在則修正
/// </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地址,
/// 對參數值就行UrlEncode 編碼後,有能夠和原鏈接不雷同
/// </summary>
/// <returns></returns>
public string GetUrl(bool EncodeValue = false)
{
StringBuilder builder = new StringBuilder();
if (!string.IsNullOrEmpty(Protocol))
{
//假如有協定
builder.Append(Protocol).Append("://");
}
//假如有主機標識
builder.Append(Host);
//假如有目次和參數
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 靜態辦法
/// <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 WordStrToA(string content)
{
Regex re = new Regex(@"(?<url>http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?)");
MatchCollection mc = re.Matches(content);
foreach (Match m in mc)
{
content = content.WordStr(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
感激浏覽,願望能贊助到年夜家,感謝年夜家對本站的支撐!