0

I have a page that is doing some actions based on the value of a query string. However I recently noticed that this breaks when the Query String contains the '&' character.

I am aware I could write some code that would translate the '&' character on the parent page but I have to believe there is a better way to do this.

Here is an example: Query string:Exercise Science & Sports Studies This only returns 'Exercise Science'

Here is the code I have to get the string:

string selectedDept = Request.QueryString [ "dept" ];

I would prefer not to encrypt the URL as the pages are sometimes linked to directly.

2
  • 2
    You need to URL encode the parameters. They should be decoded for you in Request.QueryString automatically. Commented Oct 22, 2012 at 12:59
  • 1
    use HttpUtility.UrlEncode and HttpUtility.UrlDecode Commented Oct 22, 2012 at 13:00

5 Answers 5

5

You don't need to encrypt, you need to encode the string before generating the Url.

If you are using MVC you can use:

var url = "dept=" + Url.Encode(strDept);

Otherwise you can also use:

var url = "dept=" + HttpUtility.UrlEncode(strDept);

Update:

unfortunately, this will generate an ugly URL:

dept=Exercise%20Science%20%26%20Sports%20Studies
Sign up to request clarification or add additional context in comments.

Comments

1

The ampersand (&) character is defined to separate request parameters, so there is no other way to get it inside such a parameter than to encode it.

You don't need to encrypt the parameter, just to encode it. A common encoding for this case is the so called URL encoding. The nice thing about this encoding is that normal letters and numbers stay as they are; only special characters are encoded with percent-sign sequences.

Comments

1

Yes, the & character breaks query strings. It is used as a metacharacter to separate the parameters. If you need to include a & character in a query parameter, then you have to encode it to %26. On ASP.Net, you do this with the HttpUtility.UrlEncode method, called on the Server object in page scope.

Comments

0

You should encode your parameters, like: HttpUtility.UrlEncode(myUrl);

Comments

0

The ampersand is used to delimit parameters.

You need to URL encode the parameters. They should be decoded for you in Request.QueryString automatically.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.