URL Encode and Decode in ASP.NET Core

C#asp.net CoreUrlencode

C# Problem Overview


HttpContext.Current.Server.UrlEncode

This does only work in .NET Framework. How can I encode or decode URI arguments in ASP.NET Core?

C# Solutions


Solution 1 - C#

  • 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);
}

Solution 2 - C#

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

Solution 3 - C#

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

as opposed to +;

Use:

 Uri.EscapeDataString(someString);

Solution 4 - C#

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)));

Solution 5 - C#

Just adding another approach to the mix:

UrlEncoder.Default.Encode(url);

https://docs.microsoft.com/en-us/dotnet/api/system.text.encodings.web.urlencoder?view=net-6.0

Solution 6 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionwtf512View Question on Stackoverflow
Solution 1 - C#SetView Answer on Stackoverflow
Solution 2 - C#Manuel AlvesView Answer on Stackoverflow
Solution 3 - C#ttugatesView Answer on Stackoverflow
Solution 4 - C#Jordan RyderView Answer on Stackoverflow
Solution 5 - C#MichaelView Answer on Stackoverflow
Solution 6 - C#Erti-Chris EelmaaView Answer on Stackoverflow