Rodal
Rodal

Reputation: 131

URL replace spaces with + signs

I recently created a question on how to use signs like / and + in a URL but that brought me to another question, how do I replace spaces in my URL, and why?

If my url is something.com/Find/this is my search, why is that wrong? why do we need to change it to something.com/Find/this+is+my+search

I have been searching and trying solutions for over 5 hours now. Everywhere I look the answer is the same, use httputility.urlencode or Uri.escapeDataString. But I have tried doing that like this:

string encode = Uri.EscapeDataString(TextBoxSearch.Text);
Response.Redirect("/Find/" + encode );

string encode = HttpUtility.UrlEncode(TextBoxSearch.Text);
Response.Redirect("/Find/" + encode );

string encode = encode.replace(" ", "+")
Response.Redirect("/Find/" + encode);

None of these work, they do not replace the space with anything (string.replace does but this also causes the string to change, which means it can't find values in the database on the next page).

If I encode the entire URL then all my / turn in to % and that is obviously not what I want.

What I need

If I redirect like this Response.Redirect("/Find/" + search);.
And I make a search like this "Social media".
I then get the queryString on the next page and use it to load info from my database.
Now I want to display info about Social media from my database.
but at the same time I want the url to say Find/Social+media.

EDIT:

What I try:

string encode = HttpUtility.UrlEncode(TextBoxSearch.Text);
Response.Redirect("/Find/" + encode);

This gives me a "404.11 - The request filtering module is configured to deny a request that contains a double escape sequence." on Requested URL http://localhost:65273/Find/social+media

in my Find.aspx onLoad():

IList<string> segments = Request.GetFriendlyUrlSegments();
string val = "";
for (int i = 0; i < segments.Count; i++)
    {
       val = segments[i];
    }
search = val;

Upvotes: 3

Views: 11066

Answers (2)

NightOwl888
NightOwl888

Reputation: 56849

HttpUtility.UrlEncode replaces spaces with +, but as Patrick mentioned, it is better to use %20. So, you can accomplish that using String.Replace.

var encode = TextBoxSearch.Text.Replace(" ", "%20");

That said, you should also encode the value to prevent any kinds of XSS attacks. You could do both of these by first encoding, then replacing the + from the value.

var encode = HttpUtility.UrlEncode(TextBoxSearch.Text).Replace("+", "%20");

Upvotes: 6

Patrick Hofman
Patrick Hofman

Reputation: 156918

It is perfectly fine to replace a space with %20, since that is the escaped form of a space. %20 is URL safe, so you can use that.

In fact, %20 is just the hexadecimal value of the ASCII code for space. Using HttpUtility.UrlEncode is enough.

It is better to use %20 instead of + as explained in this answer: When to encode space to plus (+) or %20?.

Upvotes: 4

Related Questions