Don't want RedirectToAction () escape characters plus

I am trying to do something similar to what Stackoverflow does.

I have a quick search text box and I can enter any number of words and submit my search. Host action does this (shortened version)

public ActionResult Search(string query) { Regex rx = new Regex("(?<word>[a-zA-Z0-9]+)"); StringBuilder parts = new StringBuilder(); foreach(Match m in rx.Matches(query)) { parts.Append(parts.Length > 0 ? "+" : string.Empty); parts.Append(m.Groups["word"]); } return RedirectToAction("Search", new { query = parts.ToString() }); ; } 

But instead

http: // localhost / search? query = word + word

I see

http: // localhost / search? query = word% 2Bword

Stackoverflow does something very similar, and I would like to do the same. I do not want my pluses to be hidden in my URLs. but I would still like to use RedirectToAction if possible.

+7
redirect escaping asp.net-mvc
source share
2 answers

Using an action result filter

I managed to solve this problem with a special filter of action results

 public class UnescapePlusAttribute: FilterAttribute, IResultFilter { public void OnResultExecuted(ResultExecutedContext filterContext) { if (filterContext.Result is RedirectToRouteResult) { string loc = filterContext.HttpContext.Response.RedirectLocation; loc = loc.Replace("%2B", "+"); filterContext.HttpContext.Response.RedirectLocation = loc; } } } 

What is it. Making my Search() method with this attribute replaced all coded pluses with actual ones. URL is now displayed as on Stackoverflow.

+3
source share

I do not think you can use RedirectToAction as you want. The problem is that it will always encode the URLs of your parameters.

I think you have to process the request yourself. My suggestion is to use Url.Action () to generate the base url, since it works the same as RedirectToAction, but returns a string. And then you have to generate a request. Please remember to use Url.Encode () for each of your query items.

I also have a suspicion that you will be able to accomplish what you need with a custom route. I am not an expert at this, but I saw something in the use of regular expressions in routes, and it could be something that is worth a look.

Edit: I came up with an easier way to do what you want. Instead of manually adding plus signs yourself, simply create the full correct URL using Url.Action (), and then replace all instances of% 20 with a plus sign. Then redo this URL. How:

 string newUrl = Url.Action("Search", new { query = query }); string plussedUrl = newUrl.Replace("%20", "+"); return new RedirectResult(plussedUrl); 
+6
source share

All Articles