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

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

我们来看看WebUtility类的定义:

using System.IO;

namespace System.Net
{
//
// 摘要:
// Provides methods for encoding and decoding URLs when processing Web requests.
public static class WebUtility
{
//
// 摘要:
// Converts a string that has been HTML-encoded for HTTP transmission into a decoded
// string.
//
// 参数:
// value:
// The string to decode.
//
// 返回结果:
// A decoded string.
public static string HtmlDecode(string value);
//
// 摘要:
// Converts a string that has been HTML-encoded into a decoded string, and sends
// the decoded string to a System.IO.TextWriter output stream.
//
// 参数:
// value:
// The string to decode.
//
// output:
// A System.IO.TextWriter stream of output.
//
// 异常:
// T:System.ArgumentNullException:
// The output parameter cannot be null if the value parameter is not null.
public static void HtmlDecode(string value, TextWriter output);
//
// 摘要:
// Converts a string to an HTML-encoded string.
//
// 参数:
// value:
// The string to encode.
//
// 返回结果:
// An encoded string.
public static string HtmlEncode(string value);
//
// 摘要:
// Converts a string into an HTML-encoded string, and returns the output as a System.IO.TextWriter
// stream of output.
//
// 参数:
// value:
// The string to encode.
//
// output:
// A System.IO.TextWriter output stream.
//
// 异常:
// T:System.ArgumentNullException:
// The output parameter cannot be null if the value parameter is not null.
public static void HtmlEncode(string value, TextWriter output);
//
// 摘要:
// Converts a string that has been encoded for transmission in a URL into a decoded
// string.
//
// 参数:
// encodedValue:
// A URL-encoded string to decode.
//
// 返回结果:
// Returns System.String. A decoded string.
public static string UrlDecode(string encodedValue);
//
// 摘要:
// Converts an encoded byte array that has been encoded for transmission in a URL
// into a decoded byte array.
//
// 参数:
// encodedValue:
// A URL-encoded System.Byte array to decode.
//
// offset:
// The offset, in bytes, from the start of the System.Byte array to decode.
//
// count:
// The count, in bytes, to decode from the System.Byte array.
//
// 返回结果:
// Returns System.Byte. A decoded System.Byte array.
public static byte[] UrlDecodeToBytes(byte[] encodedValue, int offset, int count);
//
// 摘要:
// Converts a text string into a URL-encoded string.
//
// 参数:
// value:
// The text to URL-encode.
//
// 返回结果:
// Returns System.String. A URL-encoded string.
public static string UrlEncode(string value);
//
// 摘要:
// Converts a byte array into a URL-encoded byte array.
//
// 参数:
// value:
// The System.Byte array to URL-encode.
//
// offset:
// The offset, in bytes, from the start of the System.Byte array to encode.
//
// count:
// The count, in bytes, to encode from the System.Byte array.
//
// 返回结果:
// Returns System.Byte. An encoded System.Byte array.
public static byte[] UrlEncodeToBytes(byte[] value, int offset, int count);
}
}

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

using System;
using System.Net; namespace WebUtilDemo
{
class Program
{
static void Main(string[] args)
{
string rawUri = "http://localhost:8989/home/index"; Console.WriteLine($"原始Uri地址是:{rawUri}"); string encodedUri = WebUtility.UrlEncode(rawUri); Console.WriteLine($"编码后Uri地址是:{encodedUri}");//http%3A%2F%2Flocalhost%3A8989%2Fhome%2Findex string decodedUri = WebUtility.UrlDecode(encodedUri); Console.WriteLine($"解码后Uri地址是:{decodedUri}");//http://localhost:8989/home/index Console.WriteLine("按任意键退出...");
Console.ReadKey();
}
}
}

程序运行结果如下:

所以我们看到在.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方法:

using System;
using System.Net;
using System.Web; namespace WebUtilDemo
{
class Program
{
static void Main(string[] args)
{
string rawUri = "http://ABC EFG"; Console.WriteLine($"原始Uri地址是:{rawUri}"); string encodedUri1 = WebUtility.UrlEncode(rawUri);
string encodedUri2 = HttpUtility.UrlEncode(rawUri); Console.WriteLine($"encodedUri1 是 {encodedUri1}");//http%3A%2F%2FABC+EFG
Console.WriteLine($"encodedUri2 是 {encodedUri2}");//http%3a%2f%2fABC+EFG string decodedUri1 = WebUtility.UrlDecode(encodedUri1);
string decodedUri2 = WebUtility.UrlDecode(encodedUri2); Console.WriteLine($"decodedUri1 是 {decodedUri1}");//http://ABC EFG
Console.WriteLine($"decodedUri2 是 {decodedUri2}");//http://ABC EFG string encodedUri3 = Uri.EscapeDataString(rawUri);
Console.WriteLine($"encodedUri3 是 {encodedUri3}");//http%3A%2F%2FABC%20EFG string decodedUri3 = WebUtility.UrlDecode(encodedUri3);
Console.WriteLine($"decodedUri3 是 {decodedUri3}");//http://ABC EFG Console.WriteLine("按任意键退出...");
Console.ReadKey();
}
}
}

这个问题可以参考:

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. 203--Remove LinkedList Elements

    package LinedList; public class RemoveLinkedListElements { //解法一:循环 public ListNode removeElements(L ...

  2. MySQL报错合集解决办法: server has gone away, @@GLOBAL.GTID_PURGED can only be set when @@GLOBAL.GTID_MODE = ON

    server has gone away: 如下图 执行以下命令 show global variables like '%timeout%'; set global interactive_time ...

  3. mysql日期存储格式int,timestarmp,datetime

    int (1).4个字节存储,INT的长度是4个字节,存储空间上比datatime少,int索引存储空间也相对较小,排序和查询效率相对较高一点点 (2)可读性极差,无法直观的看到数据. TIMESTA ...

  4. Django框架(十二)-- Djang与Ajax

    一.什么是Ajax AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”.即使用Javascript语言与服务器进行异步交互,传 ...

  5. Nginx编译安装脚本

      Nginx是高性能的web服务器和反向代理服务器,在互联网公司中被广泛使用.以下是Nginx在centos7系统下的一键编译安装脚本,仅供参考,具体编译参数选项请结合实际生产环境需求进行选择,脚本 ...

  6. 17 个方面,综合对比 Kafka、RabbitMQ、RocketMQ、ActiveMQ 四个分布式消息队列

    原文:https://mp.weixin.qq.com/s/lpsQ3dEZHma9H0V_mcxuTw 一.资料文档 二.开发语言 三.支持的协议 四.消息存储 五.消息事务 六.负载均衡 七.集群 ...

  7. iOS开发xib控件删不掉,修改xib运行不发生改变,修改xib不管用

    修改xib控件tag值,颜色,大小,甚至删除发现编译.运行之后效果没改变,用代码修改内容发现管用, 其实只需要clean一下!^_^ 快捷键:shift + command + k

  8. 面向对象高级A(反射,拦截方法)

    一等公民:只要可以把一个东西赋值给一个变量,这个东西就叫一等公民 断点调试 在想要加断点的地方用鼠标点击一下,会看到一个红色圆圈 变红的地方,程序执行到,就会暂停 断点应该加在报错之前,在错误代码上放 ...

  9. ZROI 暑期高端峰会 A班 Day5 杂题选讲

    CF469E \(n\) 个需要表示的数,请使用最少的 \(2^k\) 或 \(-2^k\) 表示出所有需要表示的数.输出方案. \(n\le 10^5,|a_i|\le 10^5\). 首先每个数肯 ...

  10. springboot2.x自定义拦截把static静态文件给拦截的坑

    新人新帖,喷后请指正,谢谢 1.王中王,坑中坑 和很多人一样,我在springboo自定义配置登录拦截的时候,写一个WebConfig类继承WebMvcConfigureAdapter,重写AddRe ...