Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent default url decoding in ASP.net core

In my controller I have an HTTP get method that accepts a string

[HttpGet("{token}"]
public async Task<IActionResult> GetFoo(string token) 
{
     //Some actine
     return Ok(object);
 }

If I send the below-encoded token test%2Atest, ASP .NET will decode this token to test*test by default. But if I send test%2Ftest, it does not decode the %2F to /.

I can understand why ASP.NET doesn't do that as it breaks the routes.

Is there a way to disable this default behavior so I can de the decoding in my controller?

like image 947
Ash Avatar asked Feb 21 '26 03:02

Ash


2 Answers

You need encode token when generate with using WebUtility.UrlEncode(token)

Also try to use next in controller for parsing %2F

string decodedUrl = Uri.UnescapeDataString(token);
like image 180
Alexandr Kolomoets Avatar answered Feb 22 '26 16:02

Alexandr Kolomoets


For anyone facing something similar, looking for a more "elegant" solution: just base64 encode the parameter before the request and decode it when you have to use it. I faced the same issue when sending an auto-generated email confirmation token through email and later an http request, and enconding it in base64 and decoding it when using it did the trick just fine.

like image 42
Marcos Avatar answered Feb 22 '26 17:02

Marcos