最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#Url操作類封裝、仿Node.Js中的Url模塊實(shí)例

 更新時(shí)間:2016年10月17日 09:49:22   作者:天馬3798  
這篇文章主要介紹了C#Url操作類封裝、仿Node.Js中的Url模塊,實(shí)例分析了C#Url操作類封裝的技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下。

在實(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í)例:

識(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ù)部分(帶問號(hào)) ?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">指定相對(duì)或絕對(duì)鏈接
  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>
  /// 將字符串格式化成對(duì)象時(shí)初始化處理
  /// </summary>
  private void InitParse(string url)
  {
    //判斷是否是指定協(xié)議的絕對(duì)路徑
    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 的鍵值對(duì)
  /// </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地址,
  /// 對(duì)參數(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)識(shí)
    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

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

  • C#實(shí)現(xiàn)簡易的計(jì)算器

    C#實(shí)現(xiàn)簡易的計(jì)算器

    這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)簡易的計(jì)算器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-04-04
  • C#實(shí)現(xiàn)appSettings節(jié)點(diǎn)讀取與修改的方法

    C#實(shí)現(xiàn)appSettings節(jié)點(diǎn)讀取與修改的方法

    這篇文章主要介紹了C#實(shí)現(xiàn)appSettings節(jié)點(diǎn)讀取與修改的方法,是非常實(shí)用的技巧,需要的朋友可以參考下
    2014-10-10
  • C#如何獲取枚舉的描述屬性詳解

    C#如何獲取枚舉的描述屬性詳解

    這篇文章主要給大家介紹了關(guān)于C#如何獲取枚舉的描述屬性的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-02-02
  • C# Pointer指針應(yīng)用實(shí)例簡述

    C# Pointer指針應(yīng)用實(shí)例簡述

    這篇文章主要介紹了C# Pointer指針應(yīng)用,對(duì)初學(xué)者很有借鑒學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2014-08-08
  • C#修改圖片尺寸以及不改變?cè)袌D片比例

    C#修改圖片尺寸以及不改變?cè)袌D片比例

    文章介紹了如何使用C#中的Bitmap類來修改圖片尺寸,同時(shí)保持原有的圖片比例,作者分享了自己的經(jīng)驗(yàn),并鼓勵(lì)讀者參考和使用
    2025-01-01
  • C#處理XML文件的示例詳解

    C#處理XML文件的示例詳解

    XML是一種標(biāo)記語言,是從標(biāo)準(zhǔn)通用標(biāo)記語言(SGML)中簡化修改出來的,本文主要介紹了C#處理XML文件的相關(guān)知識(shí),有需要的小伙伴可以了解一下
    2024-11-11
  • DataGridView不顯示最下面的新行、判斷新增行、刪除行操作

    DataGridView不顯示最下面的新行、判斷新增行、刪除行操作

    這篇文章介紹了DataGridView不顯示最下面的新行、判斷新增行、刪除行的操作方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-02-02
  • C#實(shí)體類轉(zhuǎn)換的兩種方式小結(jié)

    C#實(shí)體類轉(zhuǎn)換的兩種方式小結(jié)

    這篇文章主要介紹了C#實(shí)體類轉(zhuǎn)換的兩種方式小結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-01-01
  • C#中閉包的實(shí)現(xiàn)和注意事項(xiàng)詳解

    C#中閉包的實(shí)現(xiàn)和注意事項(xiàng)詳解

    閉包并不是某一個(gè)語言中特有的概念,在主流的編程語言中都有這個(gè)特性,閉包可以讓一個(gè)內(nèi)部方法可以訪問它所在外部方法中的變量,并可以對(duì)變量的值進(jìn)行修改,即使在外部方法的生命周期已經(jīng)結(jié)束后,本文給大家介紹了C#中閉包的實(shí)現(xiàn)和注意事項(xiàng),需要的朋友可以參考下
    2025-01-01
  • C#實(shí)現(xiàn)WPF項(xiàng)目復(fù)制和移動(dòng)文件夾

    C#實(shí)現(xiàn)WPF項(xiàng)目復(fù)制和移動(dòng)文件夾

    這篇文章介紹了C#實(shí)現(xiàn)WPF項(xiàng)目復(fù)制和移動(dòng)文件夾的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-03-03

最新評(píng)論

江源县| 乾安县| 延吉市| 银川市| 育儿| 呈贡县| 九寨沟县| 抚顺县| 余江县| 息烽县| 若羌县| 舒城县| 叶城县| 太和县| 丰都县| 辽宁省| 温宿县| 安福县| 米脂县| 青州市| 宕昌县| 阜宁县| 革吉县| 赣榆县| 襄城县| 石狮市| 孝昌县| 广昌县| 宜都市| 隆回县| 崇义县| 佛冈县| 株洲市| 龙泉市| 鞍山市| 信丰县| 石楼县| 花莲市| 凤庆县| 宁阳县| 长宁区|