URI formatting URL - c#

All
I have the the following lines of code... (.net 3.5)
string URL = "http://api.linkedin.com/v1/people/url=http%3a%2f%2fuk.linkedin.com%2fpub%2fjulian-welby-everard%2f0%2fb97%2f416";
UriBuilder uri = new UriBuilder(URL);
this returns a URL in the URI object of http://api.linkedin.com/v1/people/url=http://uk.linkedin.com/pub/julian-welby-everard/0/b97/416 which as been decoded, I do not what this to happen
so I tried to encoded the data twice giving
string URL = "http://api.linkedin.com/v1/people/url=http%253a%252f%252fuk.linkedin.com%252fpub%252fjulian-welby-everard%252f0%252fb97%252f416";
UriBuilder uri = new UriBuilder(URL);
this now returns the URL as follows http://api.linkedin.com/v1/people/url=http%253a%252f%252fuk.linkedin.com%252fpub%252fjulian-welby-everard%252f0%252fb97%252f416 note that it has not decoded anything this time, i was hoping that it would decode just like the first attempt but as this had been double encoded it would return the string in the correct format.
So the question is as follows, I can I stop the URI object from decoding the supplied URL so I can pass the correct data accross to the HttpWebRequest.
Julian

I believe you are looking for HttpUtility.UrlEncode("http://www.google.com/") which returns http%3a%2f%2fwww.google.com%2f.

Related

QueryString Out of Encoded URL

I have an encoded URL.
http%3a%2f%myurl.test.me%2fSometjing%2fProduct%2fSearch%3fq=Tomato
I am trying to get query string out of the url which is "Tomato". I am using the following code but it returns null.
var parsedQuery = HttpUtility.ParseQueryString((url));
Console.Write(parsedQuery["q"]); // null
You're missing a few steps. You need to decode the URL, then pull out the query string, and then parse the query string:
string decoded =
HttpUtility.UrlDecode("http%3a%2f%2fmyurl.test.me%2fSometjing%2fProduct%2fSearch%3fq=Tomato");
var uri = new Uri(decoded);
var parsedQuery = HttpUtility.ParseQueryString(uri.Query);
Console.WriteLine (parsedQuery["q"]); // Tomato
Also, your encoded URL is a little malformed. The one in your post decoded looks like this:
http:/%myurl.test.me/Sometjing/Product/Search?q=Tomato
I think you just missed a 2f after the % right before myurl.test:
http%3a%2f%2fmyurl.test.me%2fSometjing%2fProduct%2fSearch%3fq=Tomato
The URL needs to decoded first before you can use the HttpUtility.ParseQueryString().
Fair warning though mentioned directly from MSDN.
The ParseQueryString method uses query strings that might contain user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. MSDN.

Preserve an escaped Uri with HttpClient

I'm trying to use HttpClient to create a GET request with the following Uri:
http://test.com?action=enterorder&ordersource=acme&resid=urn%3Auuid%3A0c5eea50-9116-414e-8628-14b89849808d
As you can see, the resid param is escaped with %3A, ie the ":" character.
When I use this Uri in the HttpClient request, the url becomes:
http://test.com?action=enterorder&ordersource=acme&resid=urn:uuid:0c5eea50-9116-414e-8628-14b89849808d and I receive an error from the server because %3A is expected.
Anyone have any clue on what to do to preserve the escaped Uri when sending the request? It seems HttpClient always unescaped characters on the string before sending it.
Here is the code used:
Uri uri = new Uri("http://test.com?action=enterorder&ordersource=acme&resid=urn%3Auuid%3A0c5eea50-9116-414e-8628-14b89849808d");
using (HttpClient client = new HttpClient())
{
var resp = client.GetAsync(uri);
if (resp.Result.IsSuccessStatusCode)
{
var responseContent = resp.Result.Content;
string content = responseContent.ReadAsStringAsync().Result;
}
}
You may want to test in .NET 4.5 as a bunch of improvements were made to Uri parsing for escaped chars.
You can also check out this SO question: GETting a URL with an url-encoded slash which has a hack posted that you can use to force the URI to not get touched.
As a workaround you could try to encode this url part again to circumvent the issue. %3A would become %253A

How do I create a dot prefixed cookie uri?

I am trying to pass a Uri of new Uri(".example.com")
Invalid URI: The format of the URI could not be determined.
or new Uri("http://.example.com")
Invalid URI: The hostname could not be parsed.
I need to be able to use the CookieContainer.SetCookies function which only has one overload taking a Uri.
According to this page, .NET 4.0 should support dot prefixed cookies now, but it seems the Uri class does not?
In this case, you need to pass a proper uri to the function, and the Uri parser is correctly rejecting the malformed string you are trying to use.
I would advise using the Cookie Constructor that takes 4 parameters - allowing you to set the domain to a dot-prefixed one.
Cookie(string name, string value, string path, string domain);

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

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

C# decodes URL containing %2F on path, is there any way to instruct API to send the URL as it is?

I am having a URL in below format
abcd.com/xyz/pqr%2Fss/abc
I want this to be send to server as it is.
When I build Uri using System.Uri it converts it to abcd.com/xyz/pqr/ss/abc
and it fails as I don't have a URL with the specified path.
When I tried with double encoding
(abcd.com/xyz/pqr%252Fss/abc) it send the Uri as it is but it fails as server side it is converted to (abcd.com/xyz/pqr%2Fss/abc)
If you construct your uri as such:
Uri u = new Uri("http://abcd.com/xyz/pqr%2Fss/abc")
Access the encoded string like this:
u.OriginalString
I had this problem too, but I found the solution: when you use HttpUtility.UrlEncode to be sure that the application will read the url right you have to construct the link this way:
http://www.abcd.com/xyz?val=pqr%2Fss
and not like this
http://www.abcd.com/xyz/pqr%2Fss
where pqr%2Fss is the result of the HttpUtility.UrlEncode("SOME STRING")

Categories