如何将带有查询字符串的URL作为查询字符串发送

时间:2012-05-03 12:11:04

标签: c# url query-string

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

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

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

4 个答案:

答案 0 :(得分:11)

您必须将传递的网址编码为重定向网址中的参数。像这样:

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

这将创建一个没有双重'?'的正确网址和'&'字符:

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

请参阅MSDN:HttpServerUtility.UrlEncode Method

要从此已编码的网址中提取重定向网址,您必须使用HttpServerUtility.UrlDecode将其重新设置为正确的网址。

答案 1 :(得分:2)

您的查询字符串应如下所示:

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

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

你应该有一个吗?标志和所有参数与&amp ;.如果参数值只包含UrlEncode个特殊字符。

答案 2 :(得分:2)

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

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

答案 3 :(得分:0)

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