I need to get a certain part from a GET request query string. For example, if the query string is:
action=balance&id=123&session_id=123&key=3843
I would like to convert it to
action=balance&id=123&session_id=123
i.e. I would like to cut off the key parameter part. How could I do that?
After a short googling, I've found the answer here: https://www.codeproject.com/Tips/574956/How-to-get-URL-and-QueryString-value-in-an-ASP-NET
In short, you are able to retrieve what you are looking for by using the following method:
Request.ServerVariables("QUERY_STRING")
use the substring function in your language of choice
for eg. in javascript you can do it as
var f = "action=balance&id=123&session_id=123&key=3843";
var a = f.replace(f.substring(f.indexOf('&key')),"");
There are lot of other ways also.
Try
Regex.Replace(Request.RawUrl, #"&key.*", "")
string qs = Request.params;
This will return collection of all params in curre
Get the Last Index Of char '&'. Then get the substring.
string url = Request.params;
int index = url.LastIndexOf('&');
var urlWithOutKey = url.Substring(0, index);
I have investigated a little bit more and find out this solution
string url = Request.RequestUri.ToString();
Uri uri = new Uri(url);
string urlStringQuery = uri.Query;
int endIndex = urlStringQuery.IndexOf("&key", 1);
string query = urlStringQuery.Substring(1, endIndex - 1);
Related
This question already has answers here:
Get URL parameters from a string in .NET
(17 answers)
Closed 4 years ago.
I have a uri string like: http://example.com/file?a=1&b=2&c=string%20param
Is there an existing function that would convert query parameter string into a dictionary same way as ASP.NET Context.Request does it.
I'm writing a console app and not a web-service so there is no Context.Request to parse the URL for me.
I know that it's pretty easy to crack the query string myself but I'd rather use a FCL function is if exists.
Use this:
string uri = ...;
string queryString = new System.Uri(uri).Query;
var queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString);
This code by Tejs isn't the 'proper' way to get the query string from the URI:
string.Join(string.Empty, uri.Split('?').Skip(1));
You can use:
var queryString = url.Substring(url.IndexOf('?')).Split('#')[0]
System.Web.HttpUtility.ParseQueryString(queryString)
MSDN
This should work:
string url = "http://example.com/file?a=1&b=2&c=string%20param";
string querystring = url.Substring(url.IndexOf('?'));
System.Collections.Specialized.NameValueCollection parameters =
System.Web.HttpUtility.ParseQueryString(querystring);
According to MSDN. Not the exact collectiontype you are looking for, but nevertheless useful.
Edit: Apparently, if you supply the complete url to ParseQueryString it will add 'http://example.com/file?a' as the first key of the collection. Since that is probably not what you want, I added the substring to get only the relevant part of the url.
I had to do this for a modern windows app. I used the following:
public static class UriExtensions
{
private static readonly Regex _regex = new Regex(#"[?&](\w[\w.]*)=([^?&]+)");
public static IReadOnlyDictionary<string, string> ParseQueryString(this Uri uri)
{
var match = _regex.Match(uri.PathAndQuery);
var paramaters = new Dictionary<string, string>();
while (match.Success)
{
paramaters.Add(match.Groups[1].Value, match.Groups[2].Value);
match = match.NextMatch();
}
return paramaters;
}
}
Have a look at HttpUtility.ParseQueryString() It'll give you a NameValueCollection instead of a dictionary, but should still do what you need.
The other option is to use string.Split().
string url = #"http://example.com/file?a=1&b=2&c=string%20param";
string[] parts = url.Split(new char[] {'?','&'});
///parts[0] now contains http://example.com/file
///parts[1] = "a=1"
///parts[2] = "b=2"
///parts[3] = "c=string%20param"
For isolated projects, where dependencies must be kept to a minimum, I found myself using this implementation:
var arguments = uri.Query
.Substring(1) // Remove '?'
.Split('&')
.Select(q => q.Split('='))
.ToDictionary(q => q.FirstOrDefault(), q => q.Skip(1).FirstOrDefault());
Do note, however, that I do not handle encoded strings of any kind, as I was using this in a controlled setting, where encoding issues would be a coding error on the server side that should be fixed.
In a single line of code:
string xyz = Uri.UnescapeDataString(HttpUtility.ParseQueryString(Request.QueryString.ToString()).Get("XYZ"));
Microsoft Azure offers a framework that makes it easy to perform this.
http://azure.github.io/azure-mobile-services/iOS/v2/Classes/MSTable.html#//api/name/readWithQueryString:completion:
You could reference System.Web in your console application and then look for the Utility functions that split the URL parameters.
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
I'm a beginner in C# and I have the following string,
string url = "svn1/dev";
along with,
string urlMod = "ato-svn3-sslv3.of.lan/svn/dev"
I want to replace svn1 in url with "ato-svn3-sslv3.of.lan"
Although your question still has some inconsistent statements, I believe String.Replace is what you are looking for:
http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx
url = url.Replace("svn1","ato-svn3-sslv3.of.lan");
Strings are immutable so you need to assign the return value to a variable:
string replacement = "ato-svn3-sslv3.of.lan";
url = url.Replace("svn1", replacement);
You can use the string method replace.
url = url.Replace("svn1", urlMod)
I think you need this:
string url = "svn1/dev";
string anotherUrl = "ato-svn3-sslv3.of.lan/svn/dev";
string toBeReplaced = anotherUrl.Split('/')[0];
url = url.Replace("svn1", toBeReplaced);
It uses split method and replace method.
How to get text before a symbol in string ? Any ideas?
e.g. acsbkjb/123kbvh/123jh/
get text before first - "/"
Try this
string ss = myString.Split('/')[0];
You can use Substring() method to get the required part of the string.
String text="acsbkjb/123kbvh/123jh/";
int index=text.IndexOf('/');
String text2="";
if(index>=0)
text2=text.Substring(0,index);
get substring like
youstring.Substring(0,yourstring.IndexOf('/'));
The IEnumerable approach
string str = "acsbkjb/123kbvh/123jh/";
var result = new string(str.TakeWhile(a => a != '/').ToArray());
Console.WriteLine(result);
If there are no forward slashes this works without need to check the return of IndexOf
EDIT Keep this answer just as an example because the efficiency of this approach is really worse. IndexOf works faster also if you add an if statement to check the return value.
string text = "acsbkjb/123kbvh/123jh/";
string text2 = text.Substring(0, text.IndexOf("/"));
I want to get only number id from string. result : 123456
var text = "http://test/test.aspx?id=123456dfblablalab";
EDIT:
Sorry, Another number can be in the text. I want to get first number after id.
var text = "http://test/test.aspx?id=123456dfbl4564dsf";
Use:
Regex.Match(text, #"id=(\d+)").Groups[1].Value;
It depends on the context - in this case it looks like you are parsing a Uri and a query string:
var text = "http://test/test.aspx?id=123456dfblablalab";
Uri tempUri = new Uri(text);
NameValueCollection query = HttpUtility.ParseQueryString(tempUri.Query);
int number = int.Parse(new string(query["id"].TakeWhile(char.IsNumber).ToArray()));
Someone will give you a C# implementation, but it's along the lines of
/[\?\&]id\=([0-9]+)/
Which will match either &id=123456fkhkghkf or ?id=123456fjgjdfgj (so it'll get the value wherever it is in the URL) and capture the number as a match.