144
votes
HttpContext.Current.Server.UrlEncode

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

5
There is no HttpContext in ASP.NET Core - or any non-Web project. The same method is available through the methods of the Uri class, eg Uri.EscapeDataString, Uri.EscapeUriStringPanagiotis Kanavos
@PanagiotisKanavos WRONG - There is no HttpContext.Current but HttpContext is a part of .Net Core - Microsoft.AspNetCore.Http.HttpContext. Remember thisJ. Doe
Remember to read the entire comment. The HttpContext you mention is VERY different from the HttpContext of previous versions. It's far more common to use the Uri methodsPanagiotis Kanavos

5 Answers

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

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

63
votes

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

as opposed to +;

Use:

 Uri.EscapeDataString(someString);
3
votes

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
votes

Don't waste your time, kid. 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.