How to get a parameter from a URL encoded? - c#

I have the following code to get parameters and their key from a URL:
string queryString = new Uri(URL).Query;
var queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString);
var paramsList = new Dictionary<string, string>();
foreach (var parameter in queryDictionary)
{
var key = (string)parameter;
var value = System.Web.HttpUtility.ParseQueryString(queryString).Get(key);
}
It works perfect. Exception, in value, I have the decoded value. I would need to have it as it was in the address, before it was decoded. How can I do it? Note that to encoded it after gives different value in some cases.

The encoding is happening in your first line already:
string queryString = new Uri(URL).Query;
Presumably you want to avoid writing your own code to extract the Query part from a URL. Which is sensible. You can still rely on the Uri class to do the parsing for you:
var uri=new Uri(URL);
var queryString= URL.Replace(uri.GetLeftPart(UriPartial.Path), "").TrimStart('?');
———————————————————————————————————
(
var URL="http://a/b/?d= #£$%% sdf we 456 7 5?367";
var uri=new Uri(URL);
Console.WriteLine(uri.Query); // Already url-encoded by the Uri constructor
var queryString = URL.Replace(uri.GetLeftPart(UriPartial.Path), "").TrimStart('?');
Console.WriteLine(System.Web.HttpUtility.ParseQueryString(queryString)); //Not encoded!
)
(As an aside, LinqPad helps)

A possible way of doing this is to encode it back:
var encodedValue = HttpUtility.UrlEncode(value);
ASP.NET automatically calls HttpUtility.UrlDecode when you access the query string.
This is a bit dirty, but should work fine.

Related

web api call with checking part of the URL using UriTemplate not working correctly

Perhaps I do not understand how to properly use the UriTemplate
I always want to search the incoming url for
api/whatever // that is it
If URL is like below, I want to ONLY get api/CheckMainVerified
So I suppose without using UriTemplate, I guess a substring check or regex would work ?
http://localhost:29001/api/CheckMainVerified/223128
This is what I was doing
var url = "http://localhost:29001/api/CheckMainVerified/223128";
//var host = new Uri(serverHost.AbsoluteUri);
var host = new Uri("http://localhost:29001");
var apiTemplate = new UriTemplate("{api}/{*params}", true);
var match = apiTemplate.Match(host, new Uri(url));
var finalSearch = match.BoundVariables["api"];
string parameters = match.BoundVariables["params"];
finalSearch.Dump();
parameters.Dump();
match.Dump();
I think you're just missing 2nd option in the template (see example below).
var template = new UriTemplate("{api}/{controller}/{*params}", true);
var fullUri = new Uri("http://localhost:29001/api/CheckMainVerified/223128");
var prefix = new Uri("http://localhost:29001");
var results = template.Match(prefix, fullUri);
if (results != null)
{
foreach (string item in results.BoundVariables.Keys)
{
Console.WriteLine($"Key: {item}, Value: {results.BoundVariables[item]}");
// PRODUCES:
// Key: API, Value: api
// Key: CONTROLLER, Value: CheckMainVerified
// Key: PARAMS, Value: 223128
}
Console.WriteLine($"{results.BoundVariables["api"]}/{results.BoundVariables["controller"]}");
// PRODUCES:
// api/CheckMainVerified
}
As such, adding the "{controller}" to the template should resolve your issue.
From there, you could do a simple string comparison.
i.e.
if ($"{results.BoundVariables["api"]}/{results.BoundVariables["controller"]}" == "api/CheckMainVerified") { ... }
Alternatively, as you suggested; you could use a substring or regex solution.

How to get param in link by HTTP GET ASP.NET C#

My link is:
http://excample.com/default.aspx?param=1
I want to get "1" in link. And if my link is:
http://excample.com/default.aspx?param1=1&param2=0
Please help me to get the values of param1 and param2. Thank you my friend !!!
I use ASP.NET C#
You can try the below code.
Uri myUri = new Uri("http://excample.com/default.aspx?param1=1&param2=0");
string param1 = HttpUtility.ParseQueryString(myUri.Query).Get("param1");
OR
HttpContext.Current.Request.QueryString.Get("param1");
OR
Request.QueryString["param1"];
In every Request there are Form and QueryString properties.During the Request,in the Form property it contains the values which comes after submiting the form, and in QueryString it contains every parameter passed by the URL.So you need only get the QueryString from the Request and retrieve two parameters like this
var param1 = Request.QueryString["param1"]
var param2 = Request.QueryString["param2"]
You only think like this.Almost everything you need during the request is in the Request property.For parameters from query string they are in the QueryString property.
For deeply knowledge see here.https://msdn.microsoft.com/en-us/library/ms524784(v=vs.90).aspx and https://msdn.microsoft.com/en-us/library/ms525985(v=vs.90).aspx
You can try like this:
var uri = new Uri("http://excample.com/default.aspx?param=1");
var query = HttpUtility.ParseQueryString(uri.Query);
var par = query.Get("param");
or
var uri = new Uri("http://excample.com/default.aspx?param1=1&param2=0");
var query = HttpUtility.ParseQueryString(uri.Query);
var par1 = query.Get("param1");
var par2 = query.Get("param2");

Easiest way to parse "querystring" formatted data

With the following code:
string q = "userID=16555&gameID=60&score=4542.122&time=343114";
What would be the easiest way to parse the values, preferably without writing my own parser? I'm looking for something with the same functionality as Request.querystring["gameID"].
Pretty easy... Use the HttpUtility.ParseQueryString method.
Untested, but this should work:
var qs = "userID=16555&gameID=60&score=4542.122&time=343114";
var parsed = HttpUtility.ParseQueryString(qs);
var userId = parsed["userID"];
// ^^^^^^ Should be "16555". Note this will be a string of course.
You can do it with linq like this.
string query = "id=3123123&userId=44423&format=json";
Dictionary<string,string> dicQueryString =
query.Split('&')
.ToDictionary(c => c.Split('=')[0],
c => Uri.UnescapeDataString(c.Split('=')[1]));
string userId = dicQueryString["userID"];
Edit
If you can use HttpUtility.ParseQueryString then it will be a lot more straight forward and it wont be case-sensitive as in case of LinQ.
As has been mentioned in each of the previous answers, if you are in a context where you can add a dependency to the System.Web library, using HttpUtility.ParseQueryString makes sense. (For reference, the relevant source can be found in the Microsoft Reference Source). However, if this is not possible, I would like to propose the following modification to Adil's answer which accounts for many of the concerns addressed in the comments (such as case sensitivity and duplicate keys):
var q = "userID=16555&gameID=60&score=4542.122&time=343114";
var parsed = q.TrimStart('?')
.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
.Select(k => k.Split('='))
.Where(k => k.Length == 2)
.ToLookup(a => a[0], a => Uri.UnescapeDataString(a[1])
, StringComparer.OrdinalIgnoreCase);
var userId = parsed["userID"].FirstOrDefault();
var time = parsed["TIME"].Select(v => (int?)int.Parse(v)).FirstOrDefault();
If you want to avoid the dependency on System.Web that is required to use HttpUtility.ParseQueryString, you could use the Uri extension method ParseQueryString found in System.Net.Http.
Note that you have to convert the response body to a valid Uri so that ParseQueryString works.
Please also note in the MSDN document, this method is an extension method for the Uri class, so you need reference the assembly System.Net.Http.Formatting (in System.Net.Http.Formatting.dll). I tried installed it by the nuget package with the name "System.Net.Http.Formatting", and it works fine.
string body = "value1=randomvalue1&value2=randomValue2";
// "http://localhost/query?" is added to the string "body" in order to create a valid Uri.
string urlBody = "http://localhost/query?" + body;
NameValueCollection coll = new Uri(urlBody).ParseQueryString();
How is this
using System.Text.RegularExpressions;
// query example
// "name1=value1&name2=value2&name3=value3"
// "?name1=value1&name2=value2&name3=value3"
private Dictionary<string, string> ParseQuery(string query)
{
var dic = new Dictionary<string, string>();
var reg = new Regex("(?:[?&]|^)([^&]+)=([^&]*)");
var matches = reg.Matches(query);
foreach (Match match in matches) {
dic[match.Groups[1].Value] = Uri.UnescapeDataString(match.Groups[2].Value);
}
return dic;
}
System.Net.Http ParseQueryString extension method worked for me. I'm using OData query options and trying to parse out some custom parameters.
options.Request.RequestUri.ParseQueryString();
Seems to give me what I need.
HttpUtility.ParseQueryString will work as long as you are in a web app or don't mind including a dependency on System.Web. Another way to do this is:
// NameValueCollection nameValueCollection = HttpUtility.ParseQueryString(queryString);
NameValueCollection nameValueCollection = new NameValueCollection();
string[] querySegments = queryString.Split('&');
foreach(string segment in querySegments)
{
string[] parts = segment.Split('=');
if (parts.Length > 0)
{
string key = parts[0].Trim(new char[] { '?', ' ' });
string val = parts[1].Trim();
nameValueCollection.Add(key, val);
}
}
For .NET Core there is Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery
var queryString = QueryHelpers.ParseQuery("?param1=value");
var queryParamValue = queryString["param1"];
Code snippet modified from trackjs.com:

c# rewrite url parameter

I have a simple task without a simple solution.
I have a parameter in the browser that needs to be changed or rewritten
for instance www.contoso.com/countries.aspx?country=UK
all I need is to rewrite the parameter without checking the url so it might appear as:
www.contoso.com/countries.aspx?country=France
I have tried something like that but with no joy
string parameter2 = Request.QueryString["country"];
Context.RewritePath(parameter2.Replace("?country=", "France"));
You could do something like this:
var url = "www.contoso.com/countries.aspx?country={0}";
var country = "UK";
url = String.Format(url, country);
Alternatively you can do:
var url = Request.Url.AbsolutePath;
var country = Request.QueryString["country"];
url = url.Replace(country, "UK");
Then:
Response.Redirect(url);
Can you not read the whole URL into a string, split it on the '?' and then add your new bit to the first part of the string?
Something like this:
var url = Request.QueryString;
var newUrl = url.split('?');
url = newUrl[0] + "?country=France";
I dont know if that will work, its just a thought
If you want to replace the complete querystring, use
newVal = string.LastIndexOf("?");
and then
URL.Replace(oldVal, newVal);
OR if you have just one parameter in querystring and want to replace only value of it, use
newVal = string.LastIndexOf("=");
URL.Replace(oldVal, newVal);
Look at this detailed response for solution to your problem.

QueryString converted to URL-Encode using NameValueCollection

I am passing an encrypted URL string:
Default.aspx?S3tLlnIKKzE%3d
I want to pass that URL string back into the ASPX page in a variable.
protected string qs = string.Empty;
NameValueCollection qscollstring = HttpContext.Current.Request.QueryString;
qs = qscollstring[0];
Which return : S3tLlnIKKzE=
The value in qscollstring[0] is correct: S3tLlnIKKzE%3d
I understand the problem is URL-Encoding, but I cannot find a way to keep the string as is.
It seems that assigning the value from qscollstring[0] is: S3tLlnIKKzE%3d
to string changes the value : S3tLlnIKKzE=
I need to to stay: S3tLlnIKKzE%3d
Use HttpUtility.UrlEncode method to encode the string.
qs =HttpUtility.UrlEncode(qscollstring[0]);
You can also pull the value from the Uri of the current URL without having to Encode the value.
Sample:
Uri u = new Uri("http://localhost.com/default.aspx?S3tLlnIKKzE%3d");
string q = u.Query;
And part of your page:
string q = !String.IsNullOrEmpty(Request.Url.Query) && Request.Url.Query.Length > 1 ? Request.Url.Query.Substring(1) : Request.Url.Query;
Like me if you are searching for the reverse .. use
qs =HttpUtility.UrlDecode("S3tLlnIKKzE%3d");
to get back S3tLlnIKKzE=

Categories