如何将包含查询字符串的 URL 作为查询字符串发送

本文关键字:查询 字符串 URL 包含 | 更新日期: 2023-09-27 18:32:58

我正在从一个页面重定向到另一个页面,另一个重定向从第二个页面重定向到第三个页面。我从第一页开始有信息,第二页没有使用,但必须转移到第三页。是否可以将第三页的 URL 及其查询字符串作为查询字符串发送到第二页。下面是一个示例:

Response.Redirect("MyURL1?redi=MyURL2?name=me&ID=123");

我的问题是作为查询字符串发送的 URL 有两个查询字符串变量,那么系统如何知道 & 之后的内容是第二个 URL 的第二个变量,而不是第一个 URL 的第二个变量?谢谢。

如何将包含查询字符串的 URL 作为查询字符串发送

您必须对作为重定向网址中的参数传递的网址进行编码。喜欢这个:

MyURL = "MyURL1?redi=" + Server.UrlEncode("MyURL2?name=me&ID=123");

这将创建一个没有双"?"和"&"字符的正确 URL:

MyURL1?redi=MyURL2%3fname%3dme%26ID%3d123

请参阅 MSDN:HttpServerUtility.UrlEncode 方法

要从此编码的 URL 中提取重定向 URL,您必须使用 HttpServerUtility.UrlDecode 再次将其转换为正确的 URL。

查询字符串应如下所示:

MyURL1?redi=MyURL2&name=me&ID=123

检查:http://en.wikipedia.org/wiki/Query_string

你应该有一个 ? 符号和所有参数都用 &.如果参数值包含特殊字符,则只需对它们进行 Url 编码。

我发现在发送之前在 Base64 中对查询字符串参数进行编码很有帮助。在某些情况下,当您需要发送各种特殊字符时,这会有所帮助。它不能成为好的调试字符串,但它可以保护您发送的任何内容不与任何其他参数混合。

请记住,解析查询字符串的另一方也需要解析 Base64 以访问原始输入。

using System.IO;
using System.Net;
static void sendParam()
{
    // Initialise new WebClient object to send request
    var client = new WebClient();
    // Add the QueryString parameters as Name Value Collections
    // that need to go with the HTTP request, the data being sent
    client.QueryString.Add("id", "1");
    client.QueryString.Add("author", "Amin Malakoti Khah");
    client.QueryString.Add("tag", "Programming");
    // Prepare the URL to send the request to
    string url = "http://026sms.ir/getparam.aspx";
    // Send the request and read the response
    var stream = client.OpenRead(url);
    var reader = new StreamReader(stream);
    var response = reader.ReadToEnd().Trim();
    // Clean up the stream and HTTP connection
    stream.Close();
    reader.Close();
}