ASP.Net Encode Token

TL;DR – In ASP.Net MVC use the HttpServerUtility.UrlTokenEncode() and HttpServerUtility.UrlTokenDecode() for encoding and decoding tokens/keys with unprintable characters.

Every so often we use a throw away token for generating a link. An example of this would be a link to reset a password. You don’t want to send the password to your user in an email (you should never send a password to a user in an email). Instead, you create a link with a token they can click on to create a new password. Encoding the token is straight forward, however I always seem to forget the utility to use.

I always seem to go down this progression:

    • Base64 – Convert.ToBase64String()
      • Nope. This has issues with ?token= query params due to the potential `=` signs at the end.
    • Encoded using HttpUtility.UrlEncode()
      • Nope. UrlEncode does not handle unprintable characters, when you try to decode it you get the wrong results.
    • Encoded using HttpServerUtility.UrlTokenEncode()
      • YES. That’s the one we need.

Having to use the UrlTokenEncode has been fairly rare, which is why I can’t remember it immediately. The default IdentityProvider has the email reset feature built in with the encoding/decoding happening automatically. Knowing the UrlTokenEncode comes in handy when creating links for QR Codes or other purposes.