JSON encode URLs in C# like what PHP does - c#

When I use json_encode function in PHP to encode an Object in json format, it will change urls in output to an string with escape characters like http:\/\/example.com\/apps\/images\/image01.jpg however C# return a url as is i.e. http://example.com/apps/images/image01.jpg and will not add any escape characters. Since I'm going to implement a web-service just same as my old PHP web service, I want to know how can I encode a url string in C# to be the same as PHP string.

You don't need to do anything. If you write your string i.e. to file (or console) from PHP and from C# you will get the same results without changing anything.
If you really want to replace / by \/ use String.Replace() method:
string likePhp = strCSharp.Replace("/", #"\/");

You shouldn't need escaped slashes, so tell PHP not to escape them with JSON_UNESCAPED_SLASHES. Why try and hack the C# JSON to escape the slashes when it's not needed.:
echo json_encode('http://example.com/apps/images/image01.jpg', JSON_UNESCAPED_SLASHES);
Yields:
http://example.com/apps/images/image01.jpg

Related

Preparing a String to be used in Json

I have a string where I need to use as the body of a JSON object. I know its possible that the data could have quotes in it, so I parse through to add an escape character to those instance of quotes.. like so:
string NewComment = comment.Replace("\"", "\\\"");
However, somehow on some edgecases, a quote still makes it through. I don't know if this is something with UTF or some other issue, But I am trying to find a function that would safely create a json compatible string, I figured there has to be something like this out there, or a regex way of doing so.
Basically a TLDR is how to create a json syntax safe string from a c# string
The simple answer is don't do it this way. What if you have escaped quotes in your string? "Hello \"World\"" would become invalid with such a simple approach: "Hello \\"World\\"". JSON.Net or Newtonsoft are going to save you so many headaches in the long run.

Unicode literal string

I'm sending some JSON in an HTTP POST request. Some of the text within the JSON object is supposed to have superscripts.
If I create my string in C# like this:
string s = "here is my superscript: \u00B9";
... it converts the \u00B9 to the actual superscript 1, which breaks my JSON. I want the \u00B9 to show up exactly as I write it in the the string, not as a superscript.
If I add an escape character, then it shows up like:
"here is my superscript: \\u00B9"
I don't want to use an escape character, but I also don't want it to be converted to the actual superscript. Is there a way to have C# not do Unicode conversion and leave it as literally: "\u00B9"?
If I understand your question correctly... add the at symbol (#) before the string to avoid the escape sequences being processed
string s = #"here is my superscript: \u00B9";
http://msdn.microsoft.com/en-us/library/362314fe(v=vs.80).aspx
I like #NinjaNye's answer, but the other approach is to use a double-backslash to make it literal. Thus string s = "here is my superscript: \\u00B9"
is recommended you encode your string before send to server. You can encode using base64 or URLEncode in client and decode in server side.

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.

Unescape an escaped url in c#

I have urls which is escaped in this form:
http://www.someurl.com/profile.php?mode=register&agreed=true
I want to convert it to unescaped form
http://www.someurl.com/profile.php?mode=register&agreed=true
is this the same thing as escapped html?
how do i do this?
thanks
& is an HTML entity and is used when text is encoded into HTML because you have to "escape" the & that has a special meaning in HTML. Apparently, this escaping mechanism was used on the URL presumably because it is used in some HTML for instance in a link. I'm not sure why you want to decode it because the browser will do the proper decoding when the link is clicked. But anyway, to revert it you can use HttpUtility.HtmlDecode in the System.Web namespace:
var encoded = "http://www.someurl.com/profile.php?mode=register&agreed=true";
var decoded = HttpUtility.HtmlDecode(encoded);
The value of decoded is:
http://www.someurl.com/profile.php?mode=register&agreed=true
Another form of encoding/decoding used is URL encoding. This is used to be able to include special characters in parts of the URL. For instance the characters /, ? and & have a special meaning in a URL. If you need to include any of these characters in a say a query parameter you will have to URL encode the parameter to not mess up the URL. Here is an example of an URL where URL escaping has been used:
http://www.someurl.com/profile.php?company=Barnes+%26+Noble
The company name Barnes & Noble was encoded as Barnes+%26+Noble. If the & hadn't been escaped the URL would have contained not one but two query parameters because & is used as a delimiter between query parameters.
not sure why but decode from #Martin's answer doesn't work in my case (filename in my case is "%D1%8D%D1%84%D1%84%D0%B5%D0%BA%D1%82%D0%B8%D0%BD%D0%BE%D0%B2%D1%81%D1%82%D1%8C%20%D0%BF%D1%80%D0%BE%D0%B4%D0%B0%D0%B6%202020%20(1)-8.xml").
For me works method - https://learn.microsoft.com/en-us/dotnet/api/system.uri.unescape?view=netcore-3.1 .
Be aware that this is obsolete.

C# mvc2 encode url

i'm trying to encode an url with the code below;
var encodedUrl = HttpUtility.UrlEncode("http://www.example.com");
var decodedUrl = HttpUtility.UrlDecode("http%3A%2F%2Fwww%2Eexample%2Ecom%2F");
I'm working with the google webmaster tools api and this api expects an URL as shown in the decodedUrl variable above. Every single character is encoded there.
When i use the httputility encode function i get the following result;
http%3a%2f%2fwww.example.com
How can i use the encoding variable in such a way that every character in the url is encoded?
I'm pretty sure that HtmlUtility and AntiXss (another MS tool for encoding urls) aren't going to help here. A "." in a url is considered valid and so doesn't need to be encoded.
I think you're going to have to post-process your encoded string to further encode other characters that are not valid within teh google webmaster tools API.
i.e. do something like this...
var encodedUrl = HttpUtility.UrlEncode("http://www.example.com")
.Replace(".", "%2E");
... assuming that "." is the only character you're having problems with.
The period is not a reserved character in a URL, so it won't be encoded. See this question and answer for an elegant solution.

Categories