If I have a URL but as a string e.g. www.example.com?q=1234&h=4567 how can I pick out e.g. "q"
I'm picking the url up from a database so I can't use request.querystring("q")
You can use HttpUtility.ParseQueryString:
string url = new Uri("http://www.example.com?q=1234&h=4567").Query;
System.Collections.Specialized.NameValueCollection nvc = System.Web.HttpUtility.ParseQueryString(url);
foreach (string key in nvc.AllKeys)
{
// ...
}
(note that i've added the "http" to the url, otherwise you could not create an Uri)
I would try:
HttpUtility.ParseQueryString(new Uri("http://www.example.com?q=1234&h=4567").Query).Get("q")
Related
Is it possible to pass parameters with an HTTP get request? If so, how should I then do it? I have found an HTTP post requst (link). In that example the string postData is sent to a webserver. I would like to do the same using get instead. Google found this example on HTTP get here. However no parameters are sent to the web server.
My preferred way is this. It handles the escaping and parsing for you.
WebClient webClient = new WebClient();
webClient.QueryString.Add("param1", "value1");
webClient.QueryString.Add("param2", "value2");
string result = webClient.DownloadString("http://theurl.com");
First WebClient is easier to use; GET arguments are specified on the query-string - the only trick is to remember to escape any values:
string address = string.Format(
"http://foobar/somepage?arg1={0}&arg2={1}",
Uri.EscapeDataString("escape me"),
Uri.EscapeDataString("& me !!"));
string text;
using (WebClient client = new WebClient())
{
text = client.DownloadString(address);
}
In a GET request, you pass parameters as part of the query string.
string url = "http://somesite.com?var=12345";
The WebRequest object seems like too much work for me. I prefer to use the WebClient control.
To use this function you just need to create two NameValueCollections holding your parameters and request headers.
Consider the following function:
private static string DoGET(string URL,NameValueCollection QueryStringParameters = null, NameValueCollection RequestHeaders = null)
{
string ResponseText = null;
using (WebClient client = new WebClient())
{
try
{
if (RequestHeaders != null)
{
if (RequestHeaders.Count > 0)
{
foreach (string header in RequestHeaders.AllKeys)
client.Headers.Add(header, RequestHeaders[header]);
}
}
if (QueryStringParameters != null)
{
if (QueryStringParameters.Count > 0)
{
foreach (string parm in QueryStringParameters.AllKeys)
client.QueryString.Add(parm, QueryStringParameters[parm]);
}
}
byte[] ResponseBytes = client.DownloadData(URL);
ResponseText = Encoding.UTF8.GetString(ResponseBytes);
}
catch (WebException exception)
{
if (exception.Response != null)
{
var responseStream = exception.Response.GetResponseStream();
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
Response.Write(reader.ReadToEnd());
}
}
}
}
}
return ResponseText;
}
Add your querystring parameters (if required) as a NameValueCollection like so.
NameValueCollection QueryStringParameters = new NameValueCollection();
QueryStringParameters.Add("id", "123");
QueryStringParameters.Add("category", "A");
Add your http headers (if required) as a NameValueCollection like so.
NameValueCollection RequestHttpHeaders = new NameValueCollection();
RequestHttpHeaders.Add("Authorization", "Basic bGF3c2912XBANzg5ITppc2ltCzEF");
GET request with multiple params:
curl --request GET --url
http://localhost:8080/todos/?limit=10&offset=2 --header
'content-type:application/json'
You can also pass value directly via URL.
If you want to call method
public static void calling(string name){....}
then you should call usingHttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://localhost:****/Report/calling?name=Priya);
webrequest.Method = "GET";
webrequest.ContentType = "application/text";
Just make sure you are using ?Object = value in URL
How can I decode an encoded URL parameter using C#?
For example, take this URL:
my.aspx?val=%2Fxyz2F
string decodedUrl = Uri.UnescapeDataString(url)
or
string decodedUrl = HttpUtility.UrlDecode(url)
Url is not fully decoded with one call. To fully decode you can call one of this methods in a loop:
private static string DecodeUrlString(string url) {
string newUrl;
while ((newUrl = Uri.UnescapeDataString(url)) != url)
url = newUrl;
return newUrl;
}
Server.UrlDecode(xxxxxxxx)
Have you tried HttpServerUtility.UrlDecode or HttpUtility.UrlDecode?
Try:
var myUrl = "my.aspx?val=%2Fxyz2F";
var decodeUrl = System.Uri.UnescapeDataString(myUrl);
Try this:
string decodedUrl = HttpUtility.UrlDecode("my.aspx?val=%2Fxyz2F");
Is there a way to link to an internal Url in mvc5?
I get the url like so: Source = Request.RawUrl
this returns: "/Clients/AddNote"
but it can also have parameters: "/Clients/AddNote/12?items=10"
This is the code that i have so far:
string[] url = Source.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string Controller = url[0];
string Action = url[1];
try{
string id = url[2];
return RedirectToAction(Action, Controller, new { id = id});
}
catch{}
return RedirectToAction(Action, Controller);
this works good when there is only an ID ad parameter but this code does not handle the named parameters like: ?items=10
is there a way that i can just say: return RedirectToAction("/Clients/AddNote/12?items=10");?
Have you tried to use: Request.AbsoluteUri ?
I want to get the absolute root Url of an ASP.NET application dynamically. This needs to be the full root url to the application in the form: http(s)://hostname(:port)/
I have been using this static method:
public static string GetSiteRootUrl()
{
string protocol;
if (HttpContext.Current.Request.IsSecureConnection)
protocol = "https";
else
protocol = "http";
StringBuilder uri = new StringBuilder(protocol + "://");
string hostname = HttpContext.Current.Request.Url.Host;
uri.Append(hostname);
int port = HttpContext.Current.Request.Url.Port;
if (port != 80 && port != 443)
{
uri.Append(":");
uri.Append(port.ToString());
}
return uri.ToString();
}
BUT, what if I don't have HttpContext.Current in scope?
I have encountered this situation in a CacheItemRemovedCallback.
For WebForms, this code will return the absolute path of the application root, regardless of how nested the application may be:
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + ResolveUrl("~/")
The first part of the above returns the scheme and domain name of the application (http://localhost) without a trailing slash. The ResolveUrl code returns a relative path to the application root (/MyApplicationRoot/). By combining them together, you get the absolute path of the web forms application.
Using MVC:
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + Url.Content("~/")
or, if you are trying to use it directly in a Razor view:
#HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)#Url.Content("~/")
You might try getting the raw URL and trimming off everything after the path forward slash. You could also incorporate ResolveUrl("~/").
public static string GetAppUrl()
{
// This code is tested to work on all environments
var oRequest = System.Web.HttpContext.Current.Request;
return oRequest.Url.GetLeftPart(System.UriPartial.Authority)
+ System.Web.VirtualPathUtility.ToAbsolute("~/");
}
public static string GetFullRootUrl()
{
HttpRequest request = HttpContext.Current.Request;
return request.Url.AbsoluteUri.Replace(request.Url.AbsolutePath, String.Empty);
}
I've solved this by adding a web.config setting in AppSettings ("SiteRootUrl"). Simple and effective, but yet another config setting to maintain.
UrlHelper url = new UrlHelper(filterContext.RequestContext);
string helpurl = url.Action("LogOn", "Account", new { area = "" },
url.RequestContext.HttpContext.Request.Url.Scheme);
Can get you the absolute url
#saluce had an excellent idea, but his code still requires an object reference and therefore can't run in some blocks of code. With the following, as long as you have a Current.Request the following will work:
With HttpContext.Current.Request
Return .Url.GetLeftPart(UriPartial.Authority) + .ApplicationPath + If(.ApplicationPath = "/", Nothing, "/")
End With
This will work no matter the protocol, port, or root folder.
This has always worked for me
string root = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, "");
Based off Uri's but stripping query strings and handling when it is a virtual directory off IIS:
private static string GetSiteRoot()
{
string siteRoot = null;
if (HttpContext.Current != null)
{
var request = HttpContext.Current.Request;
siteRoot = request.Url.AbsoluteUri
.Replace(request.Url.AbsolutePath, String.Empty) // trim the current page off
.Replace(request.Url.Query, string.Empty); // trim the query string off
if (request.Url.Segments.Length == 4)
{
// If hosted in a virtual directory, restore that segment
siteRoot += "/" + request.Url.Segments[1];
}
if (!siteRoot.EndsWith("/"))
{
siteRoot += "/";
}
}
return siteRoot;
}
.Net's System.Web.HttpUtility class defines the following function to parse a query string into a NameValueCollection:
public static NameValueCollection ParseQueryString(string query);
Is there any function to do the reverse (i.e. to convert a NameValueCollection into a query string)?
System.Collections.Specialized.NameValueCollection does NOT support this, but a derived internal class System.Web.HttpValueCollection DOES (by overriding ToString()).
Unfortunately (being internal) you cannot instantiate this class directly, but one is returned by HttpUtility.ParseQueryString() (and you can call this with String.Empty, but not Null).
Once you have a HttpValueCollection, you can fill it from your original NameValueCollection by calling Add(), before finally calling ToString().
var nameValueCollection = new NameValueCollection {{"a","b"},{"c","d"}};
var httpValueCollection = System.Web.HttpUtility.ParseQueryString(String.Empty);
httpValueCollection.Add(nameValueCollection);
var qs = httpValueCollection.ToString();
nameValueCollection.ToString() = "System.Collections.Specialized.NameValueCollection"
httpValueCollection.ToString() = "a=b&c=d"
A NameValueCollection has an automatic ToString() method that will write all your elements out as a querystring automatically.
you don't need to write your own.
var querystringCollection = HttpUtility.ParseQueryString("test=value1&test=value2");
var output = querystringCollection.ToString();
output = "test=value1&test=value2"
I found that a combination of UriBuilder and HttpUtility classes meets my requirements to manipulate query parameters. The Uri class on its own is not enough, particularly as its Query property is read only.
var uriBuilder = new UriBuilder("http://example.com/something?param1=whatever");
var queryParameters = HttpUtility.ParseQueryString(uriBuilder.Query);
queryParameters.Add("param2", "whatever2");
queryParameters.Add("param3", "whatever2");
uriBuilder.Query = queryParameters.ToString();
var urlString = uriBuilder.Uri.ToString();
The above code results in the URL string: http://example.com/something?param1=whatever¶m2=whatever2¶m3=whatever2
Note that the ToString() goes via a Uri property, otherwise the output string would have an explicit port 80 in it.
It's nice to be able to do all this using framework classes and not have to write our own code.
I don't think there is a built in one, but here is an example of how to implement http://blog.leekelleher.com/2008/06/06/how-to-convert-namevaluecollection-to-a-query-string/
Here are 2 very useful functions that I use all the time:
private string GetQueryStringParameterValue(Uri url, string key)
{
return HttpUtility.ParseQueryString(url.Query.TrimStart('?'))[key];
}
private Uri SetQueryStringParameterValue(Uri url, string key, string value)
{
var parameters = HttpUtility.ParseQueryString(url.Query.TrimStart('?'));
parameters[key] = value;
var uriBuilder = new UriBuilder(url) { Query = parameters.ToString() };
return uriBuilder.Uri;
}