How do I send a URL with Query Strings as a Query

2020-06-08 14:50发布

问题:

I am doing a redirect from one page to another and another redirect from the second page to a third. I have imformation from the first page which is not used on the second page but must be transfered to the third page. Is it possible to send the URL of the third page with its Query Strings as a Query String to the second page. Here's an example:

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

My problem is that the URL being sent as a Query String has two Query String variables, so how will the system know that what's after the & is the second variable of the second URL and not a second variable of the first URL? Thank you.

回答1:

You must encode the url that you pass as a parameter in your redirect URL. Like this:

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

This will create a correct url without the double '?' and '&' characters:

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

See MSDN: HttpServerUtility.UrlEncode Method

To extract your redirect url from this encoded url you must use HttpServerUtility.UrlDecode to turn it into a correct url again.



回答2:

Your query string should look like this:

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

Check: http://en.wikipedia.org/wiki/Query_string

You should have one ? sign and all parameters joined with &. If parameter values contain special characters just UrlEncode them.



回答3:

I find it helpful to encode query string parameters in Base64 before sending. In some cases this helps, when you need to send all kinds of special characters. It doesn't make for good debug strings, but it will protect ANYTHING you are sending from getting mixed with any other parameters.

Just keep in mind, the other side who is parsing the query string will also need to parse the Base64 to access the original input.



回答4:

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