11

几年前,我创建了一个数据库驱动的 ASP.NET 站点,它使用单个 APSX 页面来显示所有站点页面。因此该站点的所有 URL 都采用以下格式:

/main.aspx?page=Page+Title+One

/main.aspx?page=Another+Article+Title

/main.aspx?page=Third+Page

main.aspx 页面获取查询字符串数据(例如 Page+Title+One)并将其用作从 SQL Server 数据库中拉取相应文章内容的键。页面的实际标题存储在带有空格而不是加号的数据库中(例如“页面标题一”)。

在 URL 查询字符串中使用 + 号作为单词分隔符的糟糕决定最近导致搜索引擎出现很多问题(重复内容等),所以我想修复它,但不更改 URL。

我想要做的是当搜索引擎或访问者尝试访问错误的 URL 时缺少 + 符号并使用空格,例如:

/main.aspx?page=Page Title One

我想做 301 永久重定向到:

/main.aspx?page=Page+Title+One

为了能够做到这一点,我需要检查查询字符串值是否有加号或空格,但是当我使用 Request.QueryString["page"] 获得值时,即使实际的查询字符串中有加号,我仍然会得到字符串带有空格“页面标题一”。

该站点在 IIS6/Win 2003 上运行。

我怎样才能做到这一点?

4

4 回答 4

5

Using Request["key"], it automatically converts all "+" signs into spaces. You need to use Request.RawUrl to see if there are plus signs.

Additionally, you can use System.Web.HttpUtility.ParseQueryString to parse any string query. You can just test if Request.QueryString.ToString().Contains("+") is true, and do logic from there.

于 2011-12-21T20:29:49.950 回答
3

+符号被解释为 URL 的空格。

也就是说,为了对空格进行 URL 编码,您可以使用%20+.

请参阅“对空格字符进行 URL 编码:+ 或 %20?”的SO 答案。

于 2011-12-21T20:28:42.180 回答
2

Well, of course you can't put a space in a URI in any case. What you can do is put %20 in which is the way to encode a space at any point in a URI as well as + being the normal way to encode a space in the query portion, and the recommended way to do so in that portion of it because %20 can cause problems.

Because of this is an implementaiton detail application/x-www-form-urlencoded and we normally care about the actual data sent, Request.QueryString[] does the unescaping for you, turning both + and %20 into a space.

You want to look at the Request.RawUrl (returns a string) or Request.Url which returns a Uri. Probably the easiest is to feed Request.Url into a UriBuilder so you can change just the query and get a Uri back.

Still, I'd recommend the opposite approach, if you're having issues with duplicate content due to the two possible ways of encoding a space in the query string, go with the recommended norm and turn the cases of %20 into + rather than the other way around.

var u = Request.Url;
if(u.Query.Contains("%20"))
{
    var ub = new UriBuilder(u);
    Console.WriteLine(ub.Query);
    string query = ub.Query;
    //note bug in Query property - it includes ? in get and expects it not to be there on set
    ub.Query = ub.Query.Replace("%20", "+").Substring(1);
    Response.StatusCode = 301;
    Response.RedirectLocation = ub.Uri.AbsoluteUri;
    Response.End();
}
于 2011-12-21T20:36:32.427 回答
0

You can try this :

Request.QueryString["page"].Trim();
于 2015-01-08T15:28:22.940 回答