欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

識別字符串中的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)文章

最新評論