get Request.QueryString as it show - c#

VerifyEmail.aspx?key=KMSO+tLs5zY=&val=ALKXZzxNxajUWVMaddKfPG/FcFD111CD
Request.QueryString["key"].ToString() gives me "KMSO tLs5zY="
i want key value "KMSO+tLs5zY="

If you can modify the url parameter, you can encode the values using the HttpUtility.UrlEncode method, for example:
string url = "VerifyEmail.aspx?key=" + HttpUtility.UrlEncode("KMSO+tLs5zY=");
Another method is to use Base64 encoding
string url = "VerifyEmail.aspx?key=" + EncodeTo64("KMSO+tLs5zY=");
and decoding the value reading the querystring
String value = DecodeFrom64(Request["key"]);
the code for the EncodeTo64 and DecodeFrom64 is available in this article http://arcanecode.com/2007/03/21/encoding-strings-to-base64-in-c/

Do not use %2B instead of + when producing url.
And if you get %2B's itself when requesting, do not try to replace it using
Request.QueryString["key"].ToString().Replace("%2B","+")
Use HttpUtility class' UrlEncode() method:
HttpUtility.UrlEncode("KMSO+tLs5zY=")
(:

Related

Passing a url encoded byte array

I need to pass a byte array via a URL. So I am encoding it with the UrlEncode Method like this:
string ergebnis = HttpUtility.UrlEncode(array);
The result is the following string: %00%00%00%00%00%25%b8j
Now when I pass this string in a URL like this http://localhost:51980/api/Insects?Version=%00%00%00%00%00%25%b8j
This is my Get function:
public List<TaxonDiagnosis> Get([FromUri] string version)
{
List<TaxonDiagnosis> result = new List<TaxonDiagnosis>();
result = db.TaxonDiagnosis.ToList();
byte[] array = HttpUtility.UrlDecodeToBytes(version);
if (version != null)
result = db.GetTaxonDiagnosis(array).ToList();
return result;
}
The problem is, version's value isn't %00%00%00%00%00%25%b8j. Instead it is this \0\0\0\0\0%�j. This of course causes problems when I try to decode it into a byte array again.
How can I pass the correct string in the Url?
As suggested by Jon Skeet, I encoded the arraywith a URL-safe base64 decodabet like in this post: How to achieve Base64 URL safe encoding in C#?

how to get substring or part of string from a url in c#

I have an application where uses post comments. Security is not an issue.
string url = http://example.com/xyz/xyz.html?userid=xyz&comment=Comment
What i want is to extract the userid and comment from above string.
I tried and found that i can use IndexOf and Substring to get the desired code BUT what if the userid or comment also has = symbol and & symbol then my IndexOf will return number and my Substring will be wrong.
Can you please find me a more suitable way of extracting userid and comment.
Thanks.
I got url using string url =
HttpContext.Current.Request.Url.AbsoluteUri;
Do not use AbsoluteUri property , it will give you a string Uri, instead use the Url property directly like:
var result = System.Web.HttpUtility.ParseQueryString(HttpContext.Current.Request.Url.Query);
and then you can extract each parameter like:
Console.WriteLine(result["userid"]);
Console.WriteLine(result["comment"]);
For other cases when you have string uri then do not use string operations, instead use Uri class.
Uri uri = new Uri(#"http://example.com/xyz/xyz.html?userid=xyz&comment=Comment");
You can also use TryCreate method which doesn't throw exception in case of invalid Uri.
Uri uri;
if (!Uri.TryCreate(#"http://example.com/xyz/xyz.html?userid=xyz&comment=Comment", UriKind.RelativeOrAbsolute, out uri))
{
//Invalid Uri
}
and then you can use System.Web.HttpUtility.ParseQueryString to get query string parameters:
var result = System.Web.HttpUtility.ParseQueryString(uri.Query);
The ugliest way is the following:
String url = "http://example.com/xyz/xyz.html?userid=xyz&comment=Comment";
usr = url.Split('?')[1];
usr= usr.Split('&')[0];
usr = usr.Split('=')[1];
But #habib version is better

How to send a request with data using System.Net.HttpWebRequest

I want to send simple GET request using System.Net.WebRequest. But i have a problem when I try to send on URL-s that contains "Space" character.
What i do:
string url = "https://example.com/search?text=some words&page=8";
var webRequest = System.Net.WebRequest.Create(link) as HttpWebRequest;
If i try to use this code, then webRequest.Address == "https://example.com/search?&text=some words&page=8" (#1)
I can manually add "%20" for UrlEncoded space, but "WebRequest.Create" decodes it, and again i have (#1). How can i do it right?
P.S. sorry for my English.
Try a plus sign (+) instead of space. Also drop the first ampersand (&); it is only used on non-primary arguments. As in
var url = "https://example.com/search?text=some+words&page=8";
You should make parameter values "url-friendly". To achieve that, you must "url-encode" values, using HttpUtility.UrlEncode(). This fixes not only spaces, but many other dangerous "quirks":
string val1 = "some words";
string val2 = "a <very bad> value & with specials!";
string url = "https://example.com/search?text=" + HttpUtility.UrlEncode(val1) + "&comment=" + HttpUtility.UrlEncode(val2);

Extract Parameter from Url

I have a winform application, and I would like to parse a string that represent an URL to extract some parameters.
a sample of the URL is this:
http://www.mysite.com/itm/Sector-Watch/271443634510?pt=Orologi_da_Polso&hash=item3f334d294e
the parameter I would like to extract is 271443634510 (that is, the last part of the path before the query string).
Any idea ho how this can be done?
You can use Uri.Segments, which splits up the stuff after your domain into an array that includes, for your example:
/
itm/
Sector-Watch/
271443634510
So all you need to get is the item at index 3. Working example:
string url = "http://www.mysite.com/itm/Sector-Watch/271443634510?pt=Orologi_da_Polso&hash=item3f334d294e";
Uri uri = new Uri(url);
var whatYouWant = uri.Segments[3];
You can do this:
string url = "http://www.mysite.com/itm/Sector-Watch/271443634510?pt=Orologi_da_Polso&hash=item3f334d294e";
string parameter = Regex.Match(url,"\d+(?=\?)|(?!/)\d+$").Value;
You can simply use Split function (tested and verified):
string MyUrl="http://www.mysite.com/itm/Sector-Watch/271443634510?pt=Orologi_da_Polso&hash=item3f334d294e";
string str=MyUrl.Split('/').Last().Split('?').First();

C# Cannot implicitly convert type 'string' to 'string[]' within an if else statement

I am trying to read a string into an array and I get the error "Cannot implecitly convert type 'string' to 'string[]'.
The error occurs here:
string[] sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
My full if else statement is below:
if (!string.IsNullOrEmpty(result.Tables[0].Rows[0].Field<string>("WebHTML")))
{
string[] sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
NewsContent.Text = sepText[1];
if (!string.IsNullOrEmpty(sepText[0]))
Image1.ImageUrl = sepText[0];
else
Image1.Visible = false;
NewsTitle.Text = String.Format("{3}", Extensions.GetServerName(true), result.Tables[0].Rows[0].Field<int>("News_Item_ID"), result.Tables[0].Rows[0].Field<string>("Title").UrlFormat(), result.Tables[0].Rows[0].Field<string>("Title"));
Hyperlink1.NavigateUrl = String.Format("{0}/news/{1}/{2}.aspx", Extensions.GetServerName(true), result.Tables[0].Rows[0].Field<int>("News_Item_ID"), result.Tables[0].Rows[0].Field<string>("Title").UrlFormat());
}
else
{
Hyperlink1.Visible = false;
Image1.Visible = false;
}
Thank you for your help!
EDIT Code for URL Decode:
public static string UrlDecode(this string str)
{
return System.Web.HttpUtility.UrlDecode(str);
}
result.Tables[0].Rows[0].Field<string>("WebHTML") is going to give you the value of the WebHTML field in the first row in the first table which is a single string rather than a string[].
You may want to show your code for UrlDecode() since it looks like a custom implementation rather than one of the built-in framework versions.
You also declare the UrlDecode method to take a string as a parameter and return a string. Remember, a string is not the same thing as a string array.
It seems that you are trying to put:
result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
which returns a string, into an array of strings.
Simply delare your sepText variable as a string rather than a string array and you should be good to go, e.g.:
string sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
Later in your code you will clearly need to read the contents of the string like this:
Image1.ImageUrl =sepText;
Assuming the UrlDecode you are using is the one from here then the result is a string and not a string[] !
UrlDecode returns a string and you are assigning it to an array.
If you want the parts you will have to use the string to create an Url object.
Url url = new Url(result.Tables[0].Rows[0].Field<string>("WebHTML"));
and then get the parts.
See: Get url parts without host
I don't think URLDecode works the way you think it works. All URLDecode does is remove URL encoding from a string. It does not return an array of strings - only the decoded value of the string you gave it.
http://msdn.microsoft.com/en-us/library/system.web.httputility.urldecode.aspx
Example: Your web browser replaces a space with %20. This changes the %20 back to a space.
That's because the result of this line is "string" and you're trying to assign it to an array since UrlDecode do not produce an array. What you probably wanted is to use a method split() to create an array of separators?

Categories