HttpUtility.HtmlEncode not working - c#

I am trying to encode parameters to be sent to a web service for processing.
I start with a command with parameters such as:
TransportProviderConfirmation/68,Akal Singh,+972544944860,1234
I pass this string to a the encoding function:
template = HttpUtility.HtmlEncode(template);
The returned string is not changed in any way, despite the fact that there is a blank space which should be turned into %20, and a plus sign which should be turned into %2B. What is happening?

HtmlEncode? I think you're looking for UrlEncode().

Related

C# Web Api action method automatically decoding query parameter

I have a C# Web Api end point in a controller that has a parameter. This parameter accepts an encrypted string and this string will contain characters like "/", "&", "+" etc. So whenever I call my Api endpoint from javascript, I encode it using encodeURIComponent function. Since I am expecting an encoded string I used HttpUtility.UrlDecode in my Web Api code, to decode and use it in my app.
public HttpActionResult MyAction(string encodedString)
{
string decodedString = HttpUtility.UrlDecode(encodedString);
// Process request
}
To check whether the code works as expected I started debugging by sending encoded strings as input. To my astonishment, I found that the input parameter already decodes on its own and pass it in the action method. This worked fine with the decoder method I have used, but started breaking when there was a "+" character. when I pass a string with "+" character the decoder method changed it to a blank space.
for e.g. passing djdh67-y&+dsdj to decoder changed to djdh67-y& dsdj
There were two surprises for me. First, why did the parameter got decoded on it own and second, why did the "+" character got decoded to a blank space? I cannot use this code until I understand what is happening because there might be surprises later (maybe automatic decoding stops) which will not be good.
Can someone explain me what exactly is happening or what is the best way to solve this problem?
To solve the proble just get rid of the HttpUtility.UrlDecode(encodedString) part.
The value that is coming to the action has been already decoded and you don't need to decode it second time.
In your example:
encodeURIComponent("djdh67-y&+dsdj") -> djdh67-y%26%2Bdsdj // sent
HttpUtility.UrlDecode("djdh67-y%26%2Bdsdj") -> djdh67-y&+dsdj // done
HttpUtility.UrlDecode("djdh67-y&+dsdj") -> djdh67-y& dsdj // wrong
Not encoded values in GET can be incorrectly interpret by the browser. e.g. symbol & in the request string means next parameter. That's why MVC "thinks" that every get parameter is encoded and decodes it.
In case when string is required in non-changed state it should be passed in the body of a POST request.
To add to above answer, the question of decoding + character to space is how encoding decoding works. A space is encoded to + and hence will decode it to space.
You can see the following in action when we a google search. If you type any string with spaces in the google search box and click search, check the URL, it will have a query parameter "q" which will have the search terms. These will be encoded and spaces in the terms will be converted to +

C# URL QueryString Trouble

I have a WP7 project where I am using the below code. It normally works ok, but I am getting a strange result with some particular strings being passed through.
Service = "3q%23L3t41tGfXQDTaZMbn%23w%3D%3D?f"
NavigationService.Navigate(new Uri("/Details.xaml?service=" + Service, UriKind.Relative));
Next Page:
NavigationContext.QueryString.TryGetValue("service", out Service1);
Service1 now = 3q#L3t41tGfXQDTaZMbn#w==?f
Why has the string changed?
The string hasn't changed, but you're looking at it in two different ways.
The way to encode 3q#L3t41tGfXQDTaZMbn#w==?f for as URI content is as 3q%23L3t41tGfXQDTaZMbn%23w%3D%3D?f. (Actually, it's 3q%23L3t41tGfXQDTaZMbn%23w%3D%3D%3Ff but you get away with the ? near the end not being properly escaped to %3F in this context).
Your means of writing the string, expects to receive it escaped.
Your means of reading the string, returns it unescaped.
Things are working pretty much perfectly, really.
When you need to write the string again, then just escape it again:
Service = Uri.EscapeDataString(Service1);
In your first code snippet the string is URL Encoded.
In the 2nd code snippet, the string is URL Decoded.
They are essentially the same strings, just with encoding applied/removed.
For example: urlencoding # you get %23
For further reading check out this wikipedia article on encoding.
Since HttpUtility isn't part of WP7 Silverlight stack, I'd recommend using Uri.EscapeUriString to escape any URI's that have not been escaped.
You should probably URL encode the string if you want it to pass through unscathed.

C# ASP.NET HttpWebRequest automatically decodes ampersand (&) values from query string?

Assume the following Url:
"http://server/application1/TestFile.aspx?Library=Testing&Filename=Documents & Functions + Properties.docx&Save=true"
I use HttpUtility.UrlEncode() to encode the value of the Filename parameter and I create the following Url:
"http://server/application1/TestFile.aspx?Library=Testing&Filename=Documents%20%26%20Functions%20%2B%20Properties.docx&Save=true"
I send the following (encoded version) of request from a client to a C# Web Application. On the server when I process the request I have a problem. The HttpRequest variable contains the query string partially decoded. That is to say when I try to use or quick watch the following properties of HttpRequest they have the following values.
Property = Value
================
HttpRequest.QueryString = "{Library=Testing&Filename=Documents+&+Functions+++Properties.docx&Save=true}"
HttpRequest.Url = "{http://server/application1/TestFile.aspx?Library=Testing&Filename=Documents & Functions + Properties.docx&Save=true}"
HttpRequest.Url.AbsoluteUri = "http://server/application1/TestFile.aspx?Library=Testing&Filename=Documents%20&%20Functions%20+%20Properties.docx&Save=true"
I have also checked the following properties but all of them have the & value decoded. However all other values remain properly encoded (e.g. space is %20).
HttpRequest.Url.OriginalString
HttpRequest.Url.Query
HttpRequest.Url.PathAndQuery
HttpRequest.RawUrl
There is no way I can read the value of the parameter Filename properly. Am I missing something?
The QueryString property returns a NameValueCollection object that maps the querystring keys to fully-decoded values.
You need to write Request.QueryString["FileName"].
I'm answering this question many years later because I just had this problem and figured out the solution. The problem is that HttpRequest.Url isn't really the value that you gave. HttpRequest.Url is a Uri class and that value is the ToString() value of that class. ToString() for the Uri class decodes the Url. Instead, what you want to use is HttpRequest.Url.OriginalString. That is the encoded version of the URL that you are looking for. Hope this helps some future person having this problem.
What happens when you don't use UrlEncode? You didn't show how exactly you are using the url that you created using UrlEncode, so it is quite possible that things are just being double encoded (lots of the framework will encode the URLs for you automatically).
FWIW I ran into this same problem with RavenDB (version 960). They implement their own HttpRequest object that behaves just like this -- it first decodes just the ampersands (from %26 to &) and then decodes the entire value. I believe this is a bug.
A couple of workarounds to this problem:
Implement your own query string parsing on the server. It's not fun but it is effective.
Double-encode ampersands. First encode just the ampersands in the string, then encode the entire string. (It's an easy solution but not extensible because it puts the burden on the client.)

How to use strange characters in a query string

I am using silverlight / ASP .NET and C#. What if I want to do this from silverlight for instance,
// I have left out the quotes to show you literally what the characters
// are that I want to use
string password = vtakyoj#"5
string encodedPassword = HttpUtility.UrlEncode(encryptedPassword, Encoding.UTF8);
// encoded password now = vtakyoj%23%225
URI uri = new URI("http://www.url.com/page.aspx#password=vtakyoj%23%225");
HttpPage.Window.Navigate(uri);
If I debug and look at the value of uri it shows up as this (we are still inside the silverlight app),
http://www.url.com?password=vtakyoj%23"5
So the %22 has become a quote for some reason.
If I then debug inside the page.aspx code (which of course is ASP .NET) the value of Request["password"] is actually this,
vtakyoj#"5
Which is the original value. How does that work? I would have thought that I would have to go,
HttpUtility.UrlDecode(Request["password"], Encoding.UTF8)
To get the original value.
Hope this makes sense?
Thanks.
First lets start with the UTF8 business. Esentially in this case there isn't any. When a string contains characters with in the standard ASCII character range (as your password does) a UTF8 encoding of that string is identical to a single byte ASCII string.
You start with this:-
vtakyoj#"5
The HttpUtility.UrlEncode somewhat aggressively encodes it to:-
vtakyoj%23%225
Its encoded the # and " however only # has special meaning in a URL. Hence when you view string value of the Uri object in Silverlight you see:-
vtakyoj%23"5
Edit (answering supplementary questions)
How does it know to decode it?
All data in a url must be properly encoded thats part of its being valid Url. Hence the webserver can rightly assume that all data in the query string has been appropriately encoded.
What if I had a real string which had %23 in it?
The correct encoding for "%23" would be "%3723" where %37 is %
Is that a documented feature of Request["Password"] that it decodes it?
Well I dunno, you'd have check the documentation I guess. BTW use Request.QueryString["Password"] the presence of this same indexer directly on Request was for the convenience of porting classic ASP to .NET. It doesn't make any real difference but its better for clarity since its easier to make the distinction between QueryString values and Form values.
if I don't use UFT8 the characters are being filtered out.
Aare you sure that non-ASCII characters may be present in the password? Can you provide an example you current example does not need encoding with UTF-8?
If Request["password"] is to work, you need "http://url.com?password=" + HttpUtility.UrlEncode("abc%$^##"). I.e. you need ? to separate the hostname.
Also the # syntax is username:password#hostname, but it has been disabled in IE7 and above IIRC.

QueryString malformed after URLDecode

I'm trying to pass in a Base64 string into a C#.Net web application via the QueryString. When the string arrives the "+" (plus) sign is being replaced by a space. It appears that the automatic URLDecode process is doing this. I have no control over what is being passed via the QueryString. Is there any way to handle this server side?
Example:
http://localhost:3399/Base64.aspx?VLTrap=VkxUcmFwIHNldCB0byAiRkRTQT8+PE0iIHBsdXMgb3IgbWludXMgNSBwZXJjZW50Lg==
Produces:
VkxUcmFwIHNldCB0byAiRkRTQT8 PE0iIHBsdXMgb3IgbWludXMgNSBwZXJjZW50Lg==
People have suggested URLEncoding the querystring:
System.Web.HttpUtility.UrlEncode(yourString)
I can't do that as I have no control over the calling routine (which is working fine with other languages).
There was also the suggestion of replacing spaces with a plus sign:
Request.QueryString["VLTrap"].Replace(" ", "+");
I had though of this but my concern with it, and I should have mentioned this to start, is that I don't know what other characters might be malformed in addition to the plus sign.
My main goal is to intercept the QueryString before it is run through the decoder.
To this end I tried looking at Request.QueryString.toString() but this contained the same malformed information. Is there any way to look at the raw QueryString before it is URLDecoded?
After further testing it appears that .Net expects everything coming in from the QuerString to be URL encoded but the browser does not automatically URL encode GET requests.
The suggested solution:
Request.QueryString["VLTrap"].Replace(" ", "+");
Should work just fine. As for your concern:
I had though of this but my concern with it, and I should have mentioned this to start, is that I don't know what other characters might be malformed in addition to the plus sign.
This is easy to alleviate by reading about base64. The only non alphanumeric characters that are legal in modern base64 are "/", "+" and "=" (which is only used for padding).
Of those, "+" is the only one that has special meaning as an escaped representation in URLs. While the other two have special meaning in URLs (path delimiter and query string separator), they shouldn't pose a problem.
So I think you should be OK.
You could manually replace the value (argument.Replace(' ', '+')) or consult the HttpRequest.ServerVariables["QUERY_STRING"] (even better the HttpRequest.Url.Query) and parse it yourself.
You should however try to solve the problem where the URL is given; a plus sign needs to get encoded as "%2B" in the URL because a plus otherwise represents a space.
If you don't control the inbound URLs, the first option would be preferred as you avoid the most errors this way.
I'm having this exact same issue except I have control over my URL. Even with Server.URLDecode and Server.URLEncode it doesn't convert it back to a + sign, even though my query string looks as follows:
http://localhost/childapp/default.aspx?TokenID=0XU%2fKUTLau%2bnSWR7%2b5Z7DbZrhKZMyeqStyTPonw1OdI%3d
When I perform the following.
string tokenID = Server.UrlDecode(Request.QueryString["TokenID"]);
it still does not convert the %2b back into a + sign. Instead I have to do the following:
string tokenID = Server.UrlDecode(Request.QueryString["TokenID"]);
tokenID = tokenID.Replace(" ", "+");
Then it works correctly. Really odd.
I had similar problem with a parameter that contains Base64 value and when it comes with '+'.
Only Request.QueryString["VLTrap"].Replace(" ", "+"); worked fine for me;
no UrlEncode or other encoding helping because even if you show encoded link on page yourself with '+' encoded as a '%2b' then it's browser that changes it to '+' at first when it showen and when you click it then browser changes it to empty space. So no way to control it as original poster says even if you show links yourself. The same thing with such links even in html emails.
If you use System.Uri.UnescapeDataString(yourString) it will ignore the +. This method should only be used in cases like yours where when the string was encoded using some sort of legacy approach either on the client or server.
See this blog post:
http://blogs.msdn.com/b/yangxind/archive/2006/11/09/don-t-use-net-system-uri-unescapedatastring-in-url-decoding.aspx
If you URLEncode the string before adding it to the URL you will not have any of those problems (the automatic URLDecode will return it to the original state).
Well, obviously you should have the Base64 string URLEncoded before sending it to the server.
If you cannot accomplish that, I would suggest simply replacing any embedded spaces back to +; since b64 strings are not suposed to have spaces, its a legitimate tactic...
System.Web.HttpUtility.UrlEncode(yourString) will do the trick.
As a quick hack you could replace space with plus character before base64-decoding.
I am by no means a C# developer but it looks like you need to url ENCODE your Base64 string before sending it as a url.
Can't you just assume a space is a + and replace it?
Request.QueryString["VLTrap"].Replace(" ", "+");
;)

Categories