URL Encode and Decode in ASP.NET Core

后端 未结 5 1883
花落未央
花落未央 2020-12-05 03:54
HttpContext.Current.Server.UrlEncode

It\'s only work in .NET Framework. How can I encode or decode uri arguments in ASP.NET Core project?

相关标签:
5条回答
  • 2020-12-05 04:03
    • For ASP.NET Core 2.0+ just add System.Net namespace - WebUtility class is shipped as part of System.Runtime.Extensions nuget package, that is referenced by default in ASP.NET Core project.

    • For the previous version add Microsoft.AspNetCore.WebUtilities nuget package.

    Then the WebUtility class will be available for you:

    public static class WebUtility
    {
        public static string UrlDecode(string encodedValue);
        public static string UrlEncode(string value);
    }
    
    0 讨论(0)
  • 2020-12-05 04:13

    For ASP.Net Core 2.0+ and if you need spaces to be encoded as %20

    as opposed to +;

    Use:

     Uri.EscapeDataString(someString);
    
    0 讨论(0)
  • 2020-12-05 04:25

    Don't waste your time, I've got plenty of experience with these so called url encoders, they are all useless, and have different quirks. Eg WebUtility.UrlEncode doesn't take care of "+" sign.

    If you want to encode URL parameters, employ a BASE58 encoding. It uses only alphabet letters + numbers, thus you don't need to url encode.

    0 讨论(0)
  • 2020-12-05 04:28

    I'm using a redirect, and UrlEncode did not work for me because it encodes the entire url. I solved this by instead using UriHelper.Encode, shown below.

    UriHelper.Encode

    // generate url string...
    return Redirect(Microsoft.AspNetCore.Http.Extensions.UriHelper.Encode(new System.Uri(url)));
    
    0 讨论(0)
  • 2020-12-05 04:29

    It's available on version 2.0.0 of the .Net Core SDK, in System.Net.WebUtility.UrlEncode (see documentation)

    0 讨论(0)
提交回复
热议问题