I\'ve got a string in .NET which is actually a url. I want an easy way to get the value from a particular parameter.
Normally, I\'d just use Request.Params[
Use .NET Reflector to view the FillFromString
method of System.Web.HttpValueCollection
. That gives you the code that ASP.NET is using to fill the Request.QueryString
collection.
Use static ParseQueryString
method of System.Web.HttpUtility
class that returns NameValueCollection
.
Uri myUri = new Uri("http://www.example.com?param1=good¶m2=bad");
string param1 = HttpUtility.ParseQueryString(myUri.Query).Get("param1");
Check documentation at http://msdn.microsoft.com/en-us/library/ms150046.aspx
@Andrew and @CZFox
I had the same bug and found the cause to be that parameter one is in fact: http://www.example.com?param1
and not param1
which is what one would expect.
By removing all characters before and including the question mark fixes this problem. So in essence the HttpUtility.ParseQueryString
function only requires a valid query string parameter containing only characters after the question mark as in:
HttpUtility.ParseQueryString ( "param1=good¶m2=bad" )
My workaround:
string RawUrl = "http://www.example.com?param1=good¶m2=bad";
int index = RawUrl.IndexOf ( "?" );
if ( index > 0 )
RawUrl = RawUrl.Substring ( index ).Remove ( 0, 1 );
Uri myUri = new Uri( RawUrl, UriKind.RelativeOrAbsolute);
string param1 = HttpUtility.ParseQueryString( myUri.Query ).Get( "param1" );`
This is actually very simple, and that worked for me :)
if (id == "DK")
{
string longurl = "selectServer.aspx?country=";
var uriBuilder = new UriBuilder(longurl);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query["country"] = "DK";
uriBuilder.Query = query.ToString();
longurl = uriBuilder.ToString();
}
This is probably what you want
var uri = new Uri("http://domain.test/Default.aspx?var1=true&var2=test&var3=3");
var query = HttpUtility.ParseQueryString(uri.Query);
var var2 = query.Get("var2");
HttpContext.Current.Request.QueryString.Get("id");