When I run my project I get the url http://localhost:5973/PageToPageValuePass/Default.aspx I want to Encode the URL since sometimes I need to transfer data from page to page. When the urls are encoded then it increases the reliability.
Server.UrlEncode("http://www.google.com/c#");
I get this, but how do I use it to help me encode the url?
If your encoding parts of the path:
System.Uri.EscapeUriString("c#")
If your encoding 'arguments':
String.Format( "http://something/?test={0}", System.Uri.EscapeDataString("c#") );
try this
in ASP.NET
Server.UrlEncode("http://www.google.com/c#");
in WinForms using System.Web.dll
HttpUtility.UrlEncode("http://www.google.com/c#");
Url encoding is used to ensure that special symbols included in a url (most likely in a querystring) are not mistakenly interpreted as those used in the parsing and processing of a url. For example, the + symbol is used to indicate a space in a url. However, if you were intending for a + symbol to be a part of your querystring then you would want to encode that querystring before sending it to a browser.
For example. Imagine you have written a page that receives a math equation on the querystring and displays that equation on the page.
The url might be: http://yoursite.com/displayMath.aspx?equation=3+5
The + symbol in this case is intended to be a meaningful part of the equation. However, without a UrlEncode it would be interpreted as representing a space. Reading this value from the querystring on the receiving page would yield "3 5", which is not what was intended.
Instead of redirecting to that url directly, you would want to URL encode the request first. You might write the following code:
string equation = "3+5";
string url = String.Format(#"http://yoursite.com/displayMath.aspx?equation={0}", equation);
string encodedUrl = Server.UrlEncode(url);
Response.Redirect(encodedUrl);
This would ensure that a subsequent Request.Querystring["equation"] would receive the equation intact because any special symbols would first be encoded.
I'm not sure I understand your use case for encoding urls. If you could perhaps provide more information on what you are trying to achieve I will attempt to answer more fully. For now I hope that this information is useful.
say you want to create a link with some parameters you can use it as follows:
aspx:
Click Here
code behind:
myLink.Href = Page.ResolveClientUrl("~/MyPage.aspx") + "?id=" +
Server.UrlEncode("put here what ever you want to url encode");
Or as in your question:
myLink.Href = "http://www.google.com/")+Server.UrlEncode("C#");
this will put in html:
<a id="myLink" runat="server" target="_self" href="http://www.google.com/c+c%23">
Related
i have an ashx file that requires some query-string values to deliver appropriate images.
The problem is some search engines urlencode then htmlencode those urls in their cache or when they index those.
So for example instead of getting
/preview.ashx?file=abcd.jpg&root=small
i get
/preview.ashx?file=abcd.jpg&root=small
this basically throws off the context.Request.QueryString["root"] so it thinks that there's no variable root
i guess the second key in the querystring is amp;root i.e the part after the & sign.
What i'm wondering is if there's a way to automatically html and urldecode the querystring on serverside so that the program doesn't get confused.
There is no harm in calling HttpUtility.HtmlDecode or HttpUtility.UrlDecode more than once.
string queryString = "/preview.ashx?file=abcd.jpg&root=small";
var parsedString = HttpUtility.HtmlDecode(queryString);
var root = HttpUtility.ParseQueryString(parsedString)["root"];
To URL encode and decode you can use the following methods:
string encoded = System.Web.HttpUtility.UrlEncode(url);
string decoded = System.Web.HttpUtility.UrlDecode(url);
I've seen instances in the past where the Query String has been doubly encoded. In which case you'll need to doubly decode — this may be your issue...
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.
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.
I need to extract Chinese characters from the query string in an ASP.NET web application.
When I tried it, I get "????" instead of the actual text. I know I need to decode it with UTF-8 but its does not work. I have used:
String text = System.Web.HttpUtility.UrlDecode(Request.QueryString["text"], System.Text.Encoding.UTF8);
but I get "???" back from the operation.
Please help.
There are two cases.
1st Case where your URL is real in chinese, the only function that get it is the Request.RawUrl (and not the Request.QueryString["text"]) From Request.RawUrl you need manually get your Chinese text from text=ελληνικασανκινεζικα.
2nd Case where you have first Encode your URL string before you send it. In this case the code I use is
String text = Server.UrlDecode(Request.QueryString["text"]);
Hope this help.
Note: If you try to make test with Google Chrome, then what you type on url chrome is encode/decode automatically by browser and you are not see what actual you send. Try to use ie, for make your test.
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(" ", "+");
;)