URL 用 + 号替换空格

Rod*_*dal 3 c# asp.net url urlencode

我最近创建了一个关于如何在 URL 中使用像/和这样的符号的+问题,但这让我想到了另一个问题,我如何替换 URL 中的空格,为什么?

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

我已经搜索和尝试解决方案超过 5 个小时了。我看的每个地方的答案都是一样的,使用httputility.urlencodeor Uri.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);
Run Code Online (Sandbox Code Playgroud)

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

如果我对整个 URL 进行编码,那么我/将全部转为 %,这显然不是我想要的。

我需要的

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.
Run Code Online (Sandbox Code Playgroud)

编辑:

我的尝试:

string encode = HttpUtility.UrlEncode(TextBoxSearch.Text);
Response.Redirect("/Find/" + encode);
Run Code Online (Sandbox Code Playgroud)

这给了我一个“404.11 - 请求过滤模块被配置为拒绝包含双转义序列的请求。” 在请求的 URL 上 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;
Run Code Online (Sandbox Code Playgroud)

Nig*_*888 6

HttpUtility.UrlEncode用 替换空格+,但正如帕特里克所说,最好使用%20. 因此,您可以使用String.Replace.

var encode = TextBoxSearch.Text.Replace(" ", "%20");
Run Code Online (Sandbox Code Playgroud)

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

var encode = HttpUtility.UrlEncode(TextBoxSearch.Text).Replace("+", "%20");
Run Code Online (Sandbox Code Playgroud)