URL用+符号替换空格

时间:2015-03-09 09:46:45

标签: c# asp.net url urlencode

我最近创建了一个关于如何在网址中使用/+等标记的问题,但这又引出了另一个问题,如何替换网址中的空格,为什么?

如果我的网址是something.com/Find/this is my search,为什么会出错?为什么我们需要将其更改为something.com/Find/this+is+my+search

我一直在搜索和尝试解决方案超过5个小时。无论我到哪里,答案都是一样的,使用httputility.urlencodeUri.escapeDataString。但我试过这样做:

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);

这些都不起作用,它们不会用任何东西替换空格(string.replace会这样做但这也会导致字符串发生变化,这意味着它无法在下一页的数据库中找到值)。 / p>

如果我对整个网址进行编码,那么我的所有/都会转为%,这显然不是我想要的。

我需要什么

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.

编辑:

我尝试了什么:

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

这给了我一个" 404.11 - 请求过滤模块被配置为拒绝包含双转义序列的请求。"请求网址http://localhost:65273/Find/social+media

在我的Find.aspx onLoad()中:

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

2 个答案:

答案 0 :(得分:3)

%20替换空格是完全正常的,因为这是空间的转义形式。 %20是网址安全的,因此您可以使用它。

实际上,%20只是空间ASCII code的十六进制值。使用HttpUtility.UrlEncode就足够了。

最好使用%20代替+,如本回答所述:When to encode space to plus (+) or %20?

答案 1 :(得分:2)

HttpUtility.UrlEncode+替换空格,但正如Patrick所提到的,最好使用%20。因此,您可以使用String.Replace完成此操作。

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

也就是说,您还应该编码该值以防止任何类型的XSS攻击。您可以通过首先编码,然后从值中替换+来执行这两项操作。

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