0

I'm using the RedirectToAction() method in an ASP.NET Core 2.1 controller called CatalogController:

return RedirectToAction("search", new { search_string = "example+string" });

This redirects to a URL:

catalog/search/?search_string=example%2Bstring

How do I replace the %2B encoding with a + instead?

The URL should instead look like:

catalog/search/?search_string=example+string
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77

1 Answers1

1

The RedirectToAction() method assumes that any values passed via the RouteValues parameter are not encoded; the RedirectToAction() method will take care of the URL encoding on your behalf. As such, when you enter a +, it's treating it as a literal + symbol, not an encoded space.

%2B is the correct encoding for a literal + symbol. If you want a space to be encoded in the URL, then you should enter a space in your RouteValues dictionary (e.g., search_string = "example string"). This will encode the space as a %20.

Note: A %20 is the equivalent of a + in an encoded URL, so I'm assuming that will satisfy your requirements.

If your search_string value is coming from a URL encoded source, you will need to first decode it using e.g. WebUtility.UrlDecode(). That said, if you're retrieving your search_string value from an action parameter or binding model, this decoding should already be done for you.

If, for some reason, you want to treat literal + symbols as spaces, you'll need to explicitly perform that replace on your source value (e.g., search_string.Replace("+", " ")).

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
  • Jeremy, thanks for the answer. But I searched for a solution with "+" inside URL to replace as space because I generate the string by myself. So in the next position, I saw an example at StackOverflow URL string exchange space to "-". It completely resolves my question. Bye! – Kobets Matviy Feb 04 '20 at 21:36