What's the most efficient way to get a specific parameter from a relative URL string using C#?
For example, how would you get the value of the ACTION parameter from the following relative URL string:
string url = "/page/example?ACTION=data&FOO=test";
I have already tried using:
var myUri = new Uri(url, UriKind.Relative);
String action = HttpUtility.ParseQueryString(myUri.Query).Get("ACTION");
However, I get the following error:
This operation is not supported for a relative URI.
int idx = url.IndexOf('?');
string query = idx >= 0 ? url.Substring(idx) : "";
HttpUtility.ParseQueryString(query).Get("ACTION");
While many of the URI operations are unavailable for UriKind.Relative (for whatever reason), you can build a fully qualified URI through one of the overloads that takes in a Base URI
Here's an example from the docs on Uri.Query:
Uri baseUri = new Uri ("http://www.contoso.com/");
Uri myUri = new Uri (baseUri, "catalog/shownew.htm?date=today");
Console.WriteLine(myUri.Query); // date=today
You can also get the current base from HttpContext.Current.Request.Url or even just create a mock URI base with "http://localhost" if all you care about is the path components.
So either of the following approaches should also return the QueryString from a relative path:
var path = "catalog/shownew.htm?date=today"
var query1 = new Uri(HttpContext.Current.Request.Url, path).Query;
var query2 = new Uri(new Uri("http://localhost"), path).Query;
Related
i want to convert a network path (Directory "\www.dummy.com#ABC\test") to URI:
var uri = new Uri(path, UriKind.RelativeOrAbsolute);
It occures a URIFormatException
How can i fix this?
I think you need to change UriKind enum to the Relative value.
This code snippet is working fine:
const string path = #"\www.dummy.com#ABC\test";
var uri = new Uri(path, UriKind.Relative);
Console.Write(uri);
// Output:
// \www.dummy.com#ABC\test
I don't have the Request, I only have a url string. Also, the url can either be relative or absolute. And since Uri and UriBuilder do not support relative urls, I'll probably have to do it manually, unless there is a trick I'm not aware of. This method will be used in probably more than a thousand lines of code in my project that's why I'd like to do it right.
The following code will break if a relative url is passed:
public static string AddQueryStringIfNotExists(string url, string parameter, string value)
{
var uriBuilder = new UriBuilder(url);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
if (query[parameter] == null)
{
query[parameter] = value;
uriBuilder.Query = query.ToString();
}
return uriBuilder.ToString();
}
P.S. I'm fine with doing it manually by checking whether my parameter appears after the first ? but that would require tackling several edge cases, the thing I'm trying to avoid (like a parameter name contained in another parameter)
Just check that your url is absolute. If it's not convert it to an absolute url.
Then use HttpUtility.ParseQueryString to parse the query string and add your parameter if needed.
Convert the UriBuilder back into a Uri.
If the input was an absolute Uri return the entire Uri. If the input was relative then return the relative uri.
private static Uri dummy = new Uri("http://dummy/");
public static string AddQueryStringIfNotExists(string url, string parameter, string value)
{
var uri = new Uri(url, UriKind.RelativeOrAbsolute);
var uriBuilder = uri.IsAbsoluteUri ? new UriBuilder(url) : new UriBuilder(new Uri(dummy, url));
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
if (query[parameter] == null)
{
query[parameter] = value;
uriBuilder.Query = query.ToString();
}
return uri.IsAbsoluteUri ? uriBuilder.ToString() : dummy.MakeRelativeUri(new Uri(uriBuilder.ToString())).ToString();
}
Example:
string s = AddQueryStringIfNotExists("somedirectory/mypage/html?something=1", "somethingelse", "1");
Output:
somedirectory/mypage/html?something=1&somethingelse=1
There can be a simple helper which will transform relative URL to absolute:
public static string ToAbsoluteUrl(this string url, string domain)
{
var result = url.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? url : domain + url;
return result;
}
url = "/page?skip=0";
url = url.ToAbsoluteUrl("https://example.com"); // https://example.com/page?skip=0
var uriBuilder = new UriBuilder(url);
*EDIT: This doesn't happen on Windows but on Mono 4.2.2 Linux (C# Online Compiler).
I want to parse the protocol-relative URL and get the host name etc. For now I insert "http:" to the head before processing it since C# Uri class couldn't handle a protocol-relative URL. Could you tell me if there's any better way or any good library?
// Protocol-relative URL
var uriString = "//www.example.com/bluh/bluh.css";
var uri = new Uri(uriString);
Console.WriteLine(uriString); // "//www.example.com/bluh/bluh.css"
Console.WriteLine(uri.Host); // "Empty" string
// Absolute URL
var fixUriString = uriString.StartsWith("//") ? "http:" + uriString : uriString;
var fixUri = new Uri(fixUriString);
Console.WriteLine(fixUriString); // "http://www.example.com/bluh/bluh.css"
Console.WriteLine(fixUri.Host); // "www.example.com"
This works:
Uri uri = null;
if(Uri.TryCreate("//forum.xda-developers.com/pixel-c", UriKind.Absolute, out uri))
{
Console.WriteLine(uri.Authority);
Console.WriteLine(uri.Host);
}
returns
forum.xda-developers.com
forum.xda-developers.com
It also worked for me using the Uri(string) constructor.
I have a Uri object - what property of it will give me the relative path? Of how can I decipher the relative path the file with this Uri. I am coding in c#.
use the Uri.MakeRelativeUri Method (System)
straight from MSDN:
// Create a base Uri.
Uri address1 = new Uri("http://www.contoso.com/");
// Create a new Uri from a string.
Uri address2 = new Uri("http://www.contoso.com/index.htm?date=today");
// Determine the relative Uri.
Console.WriteLine("The difference is {0}", address1.MakeRelativeUri(address2));
furthermore, if you are always looking for the relative path from the root of the domain you could also use myUri.AbsolutePath
Here's a screenie of the Uri debug view with two examples of MakeRelativeUri at the bottom using the following Uri objects
Uri myUri = new Uri("http://msdn.microsoft.com/en-us/library/system.uri.makerelativeuri.aspx#Y600");
Uri myHost = new Uri("http://msdn.microsoft.com/");
Uri myHost2 = new Uri("http://msdn.microsoft.com/en-us/");
You can add a relative path to the Uri like below.
var Url = new Uri("/something/test", UriKind.Relative);
Often I want to change just one part of a URI and get a new URI object back.
In my current dilemma, I want to append .nyud.net, to use the CoralCDN.
I have a fully qualified URI fullUri. How can I, in effect, do this:
fullUri.Host = fullUri.Host + ".nyud.net";
This needs to work for almost any URL, and the PORT of the request needs to be maintained.
Any help would be much appreciated.
You can use an UriBuilder to modify individual parts of an Uri:
Uri uri = new Uri("http://stackoverflow.com/questions/2163191/");
UriBuilder builder = new UriBuilder(uri);
builder.Host += ".nyud.net";
Uri result = builder.Uri;
// result is "http://stackoverflow.com.nyud.net/questions/2163191/"