asp .net query string encoding and decoding - asp.net

I type the following url into my web browser and press enter.
http://localhost/website.aspx?paymentID=6++7d6CZRKY%3D&language=English
Now in my code when I do HttpContext.Current.Request.QueryString["paymentID"],
I get 6 7d6CZRKY=
but when I do HttpContext.Current.Request.QueryString.ToString() I see the following:
paymentID=6++7d6CZRKY%3D&language=English
The thing I want to extract the actual payment id that the user typed in the web browser URL. I am not worried as to whether the url is encoded or not. Because I know there is a weird thing going on here %3D and + sign at the same time ! But I do need the actual + sign. Somehow it gets decoded to space when I do HttpContext.Current.Request.QueryString["paymentID"].
I just want to extract the actual payment ID that the user typed. What's the best way to do it?
Thank you.

You'll need to encode the URL first, using URLEncode(). + in URL equals a space so needs to be encoded to %2b.
string paymentId = Server.UrlEncode("6++7d6CZRKY=");
// paymentId = 6%2b%2b7d6CZRKY%3d
And now
string result = Request.QueryString["paymentId"].ToString();
//result = 6++7d6CZRKY=
However
string paymentId = Server.UrlEncode("6 7d6CZRKY=");
//paymentId looks like you want it, but the + is a space -- 6++7d6CZRKY%3d
string result = Request.QueryString["paymentId"].ToString();
//result = 6 7d6CZRKY=

There is some info on this here: Plus sign in query string.
But I suppose you could also use a regular expression to get your parameter out of the query string. Something like this:
string queryString = HttpContext.Current.Request.QueryString.ToString();
string paramPaymentID = Regex.Match(queryString, "paymentID=([^&]+)").Groups[1].Value;

I sent an Arabic text in my query string
and when I resieved this string it was Encoded
after Server.UrlDecode
departmentName = Server.UrlDecode(departmentName);
it back again to arabic
I hope this help you

Related

Accessing the query string value using ASP.NET

I have been trying to find the question to my answer but I'm unable to and finally I'm here. What I want to do is access the value passed to a webpage (GET, POST request) using asp.net. To be more clear, for example:
URL: http://www.foobar.com/SaleVoucher.aspx?sr=34
Using asp.net I want to get the sr value i.e 34.
I'm from the background of C# and new to ASP.NET and don't know much about ASP.NET.
Thanx.
Can you refer to this QueryString
Here he says how to access the query string using:
Request.Url.Query
That is not called a Header, but the Query String.
the object document.location.search will contain that and the javascript to get any query string value based on the key would be something like:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
code from other question: https://stackoverflow.com/a/901144/28004

Http.Page.Request[" "] not returning correct values

Situation:-
There is a Home.aspx page, which can be opened by a unique user ("userName" variable).
This page has a popup window control name 'alertWindow'.
In the pageLoad event of Home.aspx.cs, Welcome.aspx page is opened in the 'alertWindow' using NavigateUrl property.
The querystring passed to Welcome.aspx page contains a parameter "UserName" and this parameter is set to the logged in user's name ("userName" variable).
Now when the code execution comes to Welcome.aspx.cs page, "Request["UserName"]" is used to get\retrieve the current "userName" paramerter existing in the query string.
Issue:-
When a logged-in user's name has space or other non-usual characters, then "Request["UserName"].ToString()" doesn't retrieve the actual and correct value.
For Ex. if the logged in "userName" = "A&T Telecom", then "Request["UserName"].ToString() retrieves only "A" and nothing else.
But if the userName string is a proper value like "micheal", then "Request["UserName"].ToString() retrieves only "Micheal" correctly
Requirement:-
Please provide a way so that I get the correct value from Request["UserName"] for any kind of "userName" string value.
Home.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (user is valid)
alertWindow.NavigateUrl = "Welcome.aspx?userName=" + currentUser.ToString();
}
Welcome.aspx.cs:-
currentUserName = Request["userName"].ToString();
This is logical because you do not Encode your url. Try this:
alertWindow.NavigateUrl = "Welcome.aspx?userName=" + Server.UrlEncode(currentUser.ToString());
To say few more, they are some special characters that used on the URL, like the
: / # ? & # % + (and the space).
All that characters must be encode to a different format, so the url will not break, the UrlEncode do exactly that.
Two notes.
I select the Server to call the UrlEncode because is not depend from the Request, and you can use it inside a thread, or any function that is not called from the Page.
The Request.QueryString make UrlDecode when you use it. To get the encode url you call the Request.RawUrl
You cannot add white spaces within your url, it needs encoding so :
//uses HttpUtility.UrlEncode internally
Server.UrlEncode("something with spaces");
or
HttpUtility.UrlEncode("something with spaces");

Input string not in Correct format error while using the Google currency Conversion API

My application is in Asp.Net MVC3 coded in C#.Net.
Im using google Currency Conversion API for getting the conversion.
Google Currency Conversion API
Im passing the From Currency and To Currency values and the amount to my Controller.
Below is my C# code.
WebClient web = new WebClient();
string url = string.Format("http://www.google.com/ig/calculator?hl=en&q={2}{0}%3D%3F{1}", CurrenctCurr.ToUpper(), DestinationCurr.ToUpper(), TotCurrentPay);
string response = web.DownloadString(url);
Regex regex = new Regex("rhs: \\\"(\\d*.\\d*)");
Match match = regex.Match(response);
decimal rate = Convert.ToDecimal(match.Groups[1].Value);
Im getting an error on line
decimal rate = Convert.ToDecimal(match.Groups[1].Value.ToString());
The error is Input string not in Correct format.There is no inner exception to it.
I tried it to convert to toString()
decimal rate = Convert.ToDecimal(match.Groups[1].Value.ToString());
Also i tried to take the value of match in a string variable and then try doing a SubString logic on it.But its not working either
string test = match.ToString();
test=test.substring(0,test.Indexof("""));
There is a single Quotation ("),so im trying to take the value of string till ".
Suggest how can i solve the issue.Or what else can i try in the right direction.
Try this for getting url.
Uri uri = new Uri(string.Format("http://www.google.com/ig/calculator?hl=en&q={2}{0}%3D%3F{1}", CurrenctCurr.ToUpper(), DestinationCurr.ToUpper(), TotCurrentPay));
string url = uri.AbsoluteUri + uri.Fragment;
string response = web.DownloadString(url);

Character + is converted to %2B in HTTP Post

I'm adding functionality to a GM script we use here at work, but when trying to post (cross site may I add) to another page, my posting value of CMD is different than what it is on the page.
It's supposed to be Access+My+Account+Info but the value that is posted becomes Access%2BMy%2BAccount%2BInfo.
So I guess my question is: What's escaping my value and how do I make it not escape? And if there's no way to unescape it, does anyone have any ideas of a workaround?
Thanks!
%2B is the code for a +. You (or whatever framework you're using) should already be decoding the POST data server-side...
Just a quick remark: If you want to decode a path segment, you can use UriUtils (spring framework):
#Test
public void decodeUriPathSegment() {
String pathSegment = "some_text%2B"; // encoded path segment
String decodedText = UriUtils.decode(pathSegment, "UTF-8");
System.out.println(decodedText);
assertEquals("some_text+", decodedText);
}
Uri path segments are different from HTML escape chars (see list). Here is an example:
#Test
public void decodeHTMLEscape() {
String someString = "some_text+";
String stringJsoup = org.jsoup.parser.Parser.unescapeEntities(someString, false);
String stringApacheCommons = StringEscapeUtils.unescapeHtml4(someString);
String stringSpring = htmlUnescape(someString);
assertEquals("some_text+", stringJsoup);
assertEquals("some_text+", stringApacheCommons);
assertEquals("some_text+", stringSpring);
}
/data/v50.0/query?q=SELECT Id from Case
This worked for me. Give space instead of '+'

How to extract website hostname from full url using VB.NET?

I get ReffererUrl from current User, if refferer is exists i need to extract hostname without .com/.co.uk .... etc. value from it. So if ReffererUrl is http://main.something.biz/sup.aspx?r=e3432r3 i want to get just "something".
Doesn't matter whether it is Regex or something else.
thanks...
Note: it is just for your specs only: you can extend it by adding more condition at the end of my code. but i'd say that it wont work when path is like "abc.ss33.video.somthing.co.us"
Uri u = new Uri("http://main.something.biz/sup.aspx?r=e3432r3");
string a = u.DnsSafeHost;
string[] arr1 = a.Split('.');
string somethinVar = String.Empty;
if (arr1.Length == 3)
somethinVar = arr1[1];
There is no built-in way to do this in the sense you describe, because neither IIS nor ASP.NET knows the difference between the host name and domain name.
You have to write some code to do that.
an example could be:
string hostName=ReffererUrl.split('.')[1];
This code works only if the ReffererUrl look like the one you have posted and you have to make sure the array that the split function return an array with a number of elements greater than 1
HttpContext.Current.Request.ServerVariables("HTTP_HOST")
Extract domain with subdomain if present:-
Public Function ExtractSubAndMainDomainFromURL(URL As String) As String
'
' cut-off any url encoded data
URL = URL.Split("?"c)(0)
'return array of segments between slashes
Dim URLparts() As String = URL.Split("/"c)
'find first segment with periods/full-stops
Dim Domain As String = Array.Find(URLparts, Function(x) (x.Contains(".")))
'check if nothing returned - if necessary
If IsNothing(Domain) Then Domain = String.Empty
Return Domain
End Function

Resources