oliver
oliver

Reputation: 157

Decode parameters encoded using the JS encodeURIComponent function

I have an application that takes text entered by a user and passes it to the server as part of a URL so that an image containing the text can be rendered. The URL parameter is encoded using encodeURIComponent function.

The problem I have is that if the user enters text containing + or foreign characters I cannot get the string decoded correctly server side.

For example, If the string is "François + Anna"

The encoded URL is previewImage.ashx?id=1&text=Fran%25E7ois%2520%2B%2520Anna

On the server

Uri.UnescapeDataString( Context.Request.QueryString["text"] )

Throws an "Invalid URI: There is an invalid sequence in the string." exception. If I replace the extended character from the string, it is decoded as "Francois + Anna"

However, if I use

HttpUtility.UrlDecode(
    Context.Request.QueryString["text"], System.Text.UTF8Encoding.UTF7 )

the foreign characters are decoded correctly but the encoded + is changed to a space; "François   Anna".

Upvotes: 1

Views: 321

Answers (1)

Robert McKee
Robert McKee

Reputation: 21477

The URL wasn't encoded correctly to begin with. previewImage.ashx?id=1&text=Fran%25E7ois%2520%2B%2520Anna is not the correct URL encoding of François + Anna

I believe the correct encoding should have been previewImage.ashx?id=1&text=Fran%E7ois+%2B+Anna or previewImage.ashx?id=1&text=Fran%E7ois%20%2B%20Anna

Once the encoding has been fixed, then you should be able to retrieve the result via a simple Context.Request.QueryString["text"] call. No need to do anything special.

Upvotes: 3

Related Questions