我们在.NET Core项目中,可以用WebUtility类对Url进行编码和解码,首先我们要确保项目中引入了nuget包:System.Runtime.Extensions

当然这个nuget包默认就是包含在.NET Core的核心库中的,所以正常情况下不用单独去引入。

我们来看看WebUtility类的定义:

  1. using System.IO;
  2.  
  3. namespace System.Net
  4. {
  5. //
  6. // 摘要:
  7. // Provides methods for encoding and decoding URLs when processing Web requests.
  8. public static class WebUtility
  9. {
  10. //
  11. // 摘要:
  12. // Converts a string that has been HTML-encoded for HTTP transmission into a decoded
  13. // string.
  14. //
  15. // 参数:
  16. // value:
  17. // The string to decode.
  18. //
  19. // 返回结果:
  20. // A decoded string.
  21. public static string HtmlDecode(string value);
  22. //
  23. // 摘要:
  24. // Converts a string that has been HTML-encoded into a decoded string, and sends
  25. // the decoded string to a System.IO.TextWriter output stream.
  26. //
  27. // 参数:
  28. // value:
  29. // The string to decode.
  30. //
  31. // output:
  32. // A System.IO.TextWriter stream of output.
  33. //
  34. // 异常:
  35. // T:System.ArgumentNullException:
  36. // The output parameter cannot be null if the value parameter is not null.
  37. public static void HtmlDecode(string value, TextWriter output);
  38. //
  39. // 摘要:
  40. // Converts a string to an HTML-encoded string.
  41. //
  42. // 参数:
  43. // value:
  44. // The string to encode.
  45. //
  46. // 返回结果:
  47. // An encoded string.
  48. public static string HtmlEncode(string value);
  49. //
  50. // 摘要:
  51. // Converts a string into an HTML-encoded string, and returns the output as a System.IO.TextWriter
  52. // stream of output.
  53. //
  54. // 参数:
  55. // value:
  56. // The string to encode.
  57. //
  58. // output:
  59. // A System.IO.TextWriter output stream.
  60. //
  61. // 异常:
  62. // T:System.ArgumentNullException:
  63. // The output parameter cannot be null if the value parameter is not null.
  64. public static void HtmlEncode(string value, TextWriter output);
  65. //
  66. // 摘要:
  67. // Converts a string that has been encoded for transmission in a URL into a decoded
  68. // string.
  69. //
  70. // 参数:
  71. // encodedValue:
  72. // A URL-encoded string to decode.
  73. //
  74. // 返回结果:
  75. // Returns System.String. A decoded string.
  76. public static string UrlDecode(string encodedValue);
  77. //
  78. // 摘要:
  79. // Converts an encoded byte array that has been encoded for transmission in a URL
  80. // into a decoded byte array.
  81. //
  82. // 参数:
  83. // encodedValue:
  84. // A URL-encoded System.Byte array to decode.
  85. //
  86. // offset:
  87. // The offset, in bytes, from the start of the System.Byte array to decode.
  88. //
  89. // count:
  90. // The count, in bytes, to decode from the System.Byte array.
  91. //
  92. // 返回结果:
  93. // Returns System.Byte. A decoded System.Byte array.
  94. public static byte[] UrlDecodeToBytes(byte[] encodedValue, int offset, int count);
  95. //
  96. // 摘要:
  97. // Converts a text string into a URL-encoded string.
  98. //
  99. // 参数:
  100. // value:
  101. // The text to URL-encode.
  102. //
  103. // 返回结果:
  104. // Returns System.String. A URL-encoded string.
  105. public static string UrlEncode(string value);
  106. //
  107. // 摘要:
  108. // Converts a byte array into a URL-encoded byte array.
  109. //
  110. // 参数:
  111. // value:
  112. // The System.Byte array to URL-encode.
  113. //
  114. // offset:
  115. // The offset, in bytes, from the start of the System.Byte array to encode.
  116. //
  117. // count:
  118. // The count, in bytes, to encode from the System.Byte array.
  119. //
  120. // 返回结果:
  121. // Returns System.Byte. An encoded System.Byte array.
  122. public static byte[] UrlEncodeToBytes(byte[] value, int offset, int count);
  123. }
  124. }

现在我们新建一个.NET Core控制台项目,来演示WebUtility类的简单用法,代码如下:

  1. using System;
  2. using System.Net;
  3.  
  4. namespace WebUtilDemo
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. string rawUri = "http://localhost:8989/home/index";
  11.  
  12. Console.WriteLine($"原始Uri地址是:{rawUri}");
  13.  
  14. string encodedUri = WebUtility.UrlEncode(rawUri);
  15.  
  16. Console.WriteLine($"编码后Uri地址是:{encodedUri}");//http%3A%2F%2Flocalhost%3A8989%2Fhome%2Findex
  17.  
  18. string decodedUri = WebUtility.UrlDecode(encodedUri);
  19.  
  20. Console.WriteLine($"解码后Uri地址是:{decodedUri}");//http://localhost:8989/home/index
  21.  
  22. Console.WriteLine("按任意键退出...");
  23. Console.ReadKey();
  24. }
  25. }
  26. }

程序运行结果如下:

所以我们看到在.NET Core中使用WebUtility类,可以很方便地对Url进行编码和解码。

WebUtility.UrlEncode和HttpUtility.UrlEncode的空格转换问题

目前.NET Core中WebUtility.UrlEncode方法会将空格" "转换为加号"+",然而空格" "的Url编码应该是"%20",不知道这是不是目前.NET Core的一个Bug,因为这个问题实际上在WebUtility.UrlEncode和HttpUtility.UrlEncode两个方法中都存在。

但是也有说法,在Url编码中空格" ",既可以用加号"+"表示,也可以用"%20"表示,所以这也不一定是个Bug。

如果要将空格" "编码为"%20",可以使用Uri.EscapeDataString方法:

  1. using System;
  2. using System.Net;
  3. using System.Web;
  4.  
  5. namespace WebUtilDemo
  6. {
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. string rawUri = "http://ABC EFG";
  12.  
  13. Console.WriteLine($"原始Uri地址是:{rawUri}");
  14.  
  15. string encodedUri1 = WebUtility.UrlEncode(rawUri);
  16. string encodedUri2 = HttpUtility.UrlEncode(rawUri);
  17.  
  18. Console.WriteLine($"encodedUri1 是 {encodedUri1}");//http%3A%2F%2FABC+EFG
  19. Console.WriteLine($"encodedUri2 是 {encodedUri2}");//http%3a%2f%2fABC+EFG
  20.  
  21. string decodedUri1 = WebUtility.UrlDecode(encodedUri1);
  22. string decodedUri2 = WebUtility.UrlDecode(encodedUri2);
  23.  
  24. Console.WriteLine($"decodedUri1 是 {decodedUri1}");//http://ABC EFG
  25. Console.WriteLine($"decodedUri2 是 {decodedUri2}");//http://ABC EFG
  26.  
  27. string encodedUri3 = Uri.EscapeDataString(rawUri);
  28. Console.WriteLine($"encodedUri3 是 {encodedUri3}");//http%3A%2F%2FABC%20EFG
  29.  
  30. string decodedUri3 = WebUtility.UrlDecode(encodedUri3);
  31. Console.WriteLine($"decodedUri3 是 {decodedUri3}");//http://ABC EFG
  32.  
  33. Console.WriteLine("按任意键退出...");
  34. Console.ReadKey();
  35. }
  36. }
  37. }

这个问题可以参考:

URL Encode and Decode in ASP.NET Core

.NET Core中如何对Url进行编码和解码的更多相关文章

  1. java中URL 的编码和解码函数

    java中URL 的编码和解码函数java.net.URLEncoder.encode(String s)和java.net.URLDecoder.decode(String s);在javascri ...

  2. url在线编码和解码

    在工作中,经常遇到encode之后的url.想查看里面的某个参数的时候,很不直观.今天在网上搜了一下对url在线编码和解码的网站.对我来说,使用起来很方便.而且这个网站里面,不仅仅有对url的编码和解 ...

  3. URL的编码和解码

    URL的编码和解码 参考:阮一峰--关于URL编码 1 为什么要URL编码 在因特网上传送URL,只能采用ASCII字符集 也就是说URL只能使用英文字母.阿拉伯数字和某些标点符号,不能使用其他文字和 ...

  4. javascript对url进行编码和解码

    这里总结下JavaScript对URL进行编码和解码的三个方法. 为什么要对URL进行编码和解码 只有[0-9[a-Z] $ - _ . + ! * ' ( ) ,]以及某些保留字,才能不经过编码直接 ...

  5. PHP中对汉字进行UNICODE编码和解码的实现

    <?php /** PHP中对汉字进行UNICODE编码和解码的实现 **/ class Helper_Tool{ //php中的unicode编码转中文 static function uni ...

  6. 在线url网址编码、解码

    >>在线url网址编码.解码<<

  7. JS对url进行编码和解码(三种方式区别)

    Javascript语言用于编码的函数,一共有三个,最古老的一个就是escape().虽然这个函数现在已经不提倡使用了,但是由于历史原因,很多地方还在使用它,所以有必要先从它讲起. escape 和 ...

  8. URL地址编码和解码

    0. 参考 [整理]关于http(GET或POST)请求中的url地址的编码(encode)和解码(decode) python3中的urlopen对于中文url是如何处理的? 中文URL的编码问题 ...

  9. js对url进行编码和解码

    编码 只有 0-9[a-Z] $ - _ . + ! * ' ( ) , 以及某些保留字,才能不经过编码直接用于 URL. 例如:搜索的中文关键字,复制网址之后再粘贴就会发现该URL已经被转码. 1. ...

随机推荐

  1. Idea中Spring整合MyBatis框架中配置文件中对象注入问题解决方案

    运行环境:Spring框架整合MaBitis框架 问题叙述: 在Spring配置文件applicationContext-mybatis.xml中配置好mybatis之后 <?xml versi ...

  2. UE4 Keynote 1

    [UE4 Keynote 1] 1.U3D中的Project,在UE4中叫 ContentBrowser,中文名叫“内容浏览器” 最多可以打开4个ContentBrowser,通过 “窗口” -> ...

  3. 大数据技术原理与应用【第五讲】NoSQL数据库:5.1 NoSQL概论&5.2 NoSQL与关系数据库的比较

    5.1 NoSQL概论 最初:反SQL 概念演变,现在:Not only SQL 特点: 1.灵活的可扩展性 所以支持海量数据存储 2.灵活的数据模型 例如:HBase 3.和云计算的紧密结合 (一) ...

  4. Extended Traffic LightOJ - 1074

    题目链接:https://vjudge.net/problem/LightOJ-1074 思路:(busyness of destination - busyness of source)3 可能会是 ...

  5. D. Maxim and Array

    https://www.cnblogs.com/qscqesze/p/5925893.html  原博客 http://codeforces.com/group/1EzrFFyOc0/contest/ ...

  6. Codeforces 749E: Inversions After Shuffle

    题目传送门:CF749E. 记一道傻逼计数题. 题意简述: 给一个 \(1\) 到 \(n\) 的排列,随机选取区间 \([l,r]\) 随机打乱区间内的元素,问打乱后的整个序列的逆序数期望. 题解: ...

  7. func_get_args call_user_func_array

    <?php //call_user_func_array.php function test($arg1,$arg2) { $t_args = func_get_args(); $t_resul ...

  8. USACO Roadblock

    洛谷 P2176 [USACO14FEB]路障Roadblock 洛谷传送门 JDOJ 2406: USACO 2014 Feb Silver 2.Roadblock JDOJ传送门1 JDOJ 24 ...

  9. jdbc笔记2

    private static String driver; private static String url; private static String username; private sta ...

  10. 知识点6 C++数据类型转换 string

    一.int转string 1.c++11标准增加了全局函数std::to_string: string to_string (int val); string to_string (long val) ...