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["theThingIWant"]
, but this string isn't from the request. I can create a new Uri
item like so:
Uri myUri = new Uri(TheStringUrlIWantMyValueFrom);
I can use myUri.Query
to get the query string...but then I apparently have to find some regexy way of splitting it up.
Am I missing something obvious, or is there no built in way to do this short of creating a regex of some kind, etc?
Use .NET Reflector to view the
FillFromString
method ofSystem.Web.HttpValueCollection
. That gives you the code that ASP.NET is using to fill theRequest.QueryString
collection.Use static
ParseQueryString
method ofSystem.Web.HttpUtility
class that returnsNameValueCollection
.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 notparam1
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:My workaround:
if you want in get your QueryString on Default page .Default page means your current page url . you can try this code :
Here's another alternative if, for any reason, you can't or don't want to use
HttpUtility.ParseQueryString()
.This is built to be somewhat tolerant to "malformed" query strings, i.e.
http://test/test.html?empty=
becomes a parameter with an empty value. The caller can verify the parameters if needed.Test
Or if you don't know the URL (so as to avoid hardcoding, use the
AbsoluteUri
Example ...