.NET Core中如何對Url進行編碼和解碼


我們在.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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM