.NET Core URL编码

在现代的Web开发中,我们经常需要处理URL的编码和解码。URL编码是将URL中的特殊字符转换为特定格式的过程,以保证URL能够正确传输和解析。在.NET Core中,我们可以使用System.Net.WebUtility.UrlEncodeSystem.Net.WebUtility.UrlDecode方法来进行URL编码和解码。

URL编码

URL编码是将URL中的非字母数字字符转换为百分号编码的过程。在URL中,某些字符具有特殊含义,比如用于表示路径分隔符、查询参数分隔符等。如果我们需要在URL中包含这些特殊字符,我们需要将它们进行编码。URL编码使用百分号加上两位十六进制数来表示特殊字符。

在.NET Core中,我们可以使用System.Net.WebUtility.UrlEncode方法来进行URL编码。以下是一个简单的示例:

string url = " core";
string encodedUrl = WebUtility.UrlEncode(url);

Console.WriteLine(encodedUrl);

输出结果为:

https%3A%2F%2Fwww.example.com%2Fsearch%3Fq%3Ddotnet+core

可以看到,特殊字符:/?都被进行了编码。

URL解码

URL解码是将URL中的百分号编码转换回原始字符的过程。在接收到URL时,我们通常需要对URL进行解码,以便正确地解析和处理。在.NET Core中,我们可以使用System.Net.WebUtility.UrlDecode方法来进行URL解码。以下是一个简单的示例:

string encodedUrl = "https%3A%2F%2Fwww.example.com%2Fsearch%3Fq%3Ddotnet+core";
string decodedUrl = WebUtility.UrlDecode(encodedUrl);

Console.WriteLine(decodedUrl);

输出结果为:

 core

可以看到,编码后的URL被成功解码。

URL编码和解码的应用场景

URL编码和解码在Web开发中有着广泛的应用场景。以下是一些常见的应用场景:

1. 查询字符串参数

在Web应用程序中,我们经常会使用查询字符串参数来传递数据。如果查询字符串参数中包含特殊字符或非ASCII字符,我们需要对其进行URL编码。在服务器端接收到查询字符串参数后,我们通常需要对其进行URL解码以获取原始数据。

例如,如果我们要向服务器发送以下查询字符串参数:

name=John Doe&email=john.doe@example.com

我们可以使用WebUtility.UrlEncode方法对其进行编码:

string name = "John Doe";
string email = "john.doe@example.com";

string encodedQueryString = $"name={WebUtility.UrlEncode(name)}&email={WebUtility.UrlEncode(email)}";

Console.WriteLine(encodedQueryString);

输出结果为:

name=John+Doe&email=john.doe%40example.com

在服务器端接收到查询字符串参数后,我们可以使用WebUtility.UrlDecode方法对其进行解码:

string encodedQueryString = "name=John+Doe&email=john.doe%40example.com";

string[] parameters = encodedQueryString.Split('&');
foreach (string parameter in parameters)
{
    string[] parts = parameter.Split('=');
    string key = parts[0];
    string value = WebUtility.UrlDecode(parts[1]);

    Console.WriteLine($"{key}: {value}");
}

输出结果为:

name: John Doe
email: john.doe@example.com

2. URL路径和片段

URL中的路径和片段也可能包含特殊字符或非ASCII字符。在构建URL时,我们需要对路径和片段进行URL编码以确保URL的正确性。在服务器端接收到URL时,我们需要对路径和片段进行URL解码以获取原始数据。

例如,如果我们要构建以下URL:


我们可以使用WebUtility.UrlEncode方法对路径和片段进行编码:

string keyword = "keyword with spaces";
string section = "section1";

string encodedPath = $"/search/{WebUtility.UrlEncode(keyword)}";
string encodedUrl = $"