简体   繁体   中英

How can I pull a value out of a QueryString-like string with C#

I have an ASP.NET page that has a value stored in the session object.

I want to pull a value out for a specific key -- but remember it's just a string.

Take for example the string below -- what's the best way to get "FOOBAR" from this string? Is regex the best way?

sometimes it could appear this way:

"?facets=All Groups||Brand&TitleTag=FOOBAR#back"

other times it could appear this way:

"?facets=All Groups||Brand&TitleTag=FOOBAR"

UPDATE: SOLUTION

Thanks jglouie for the idea to use 'ParseQueryString' -- that ultimately did the trick. The code sample you provided was a good start. Below is my final solution:

System.Collections.Specialized.NameValueCollection pairs = HttpUtility.ParseQueryString(facetStateOrURL);
string titleTagValue = pairs["TitleTag"];
if (!String.IsNullOrEmpty(titleTagValue) && titleTagValue.IndexOf('#') > -1)
{
    titleTagValue = titleTagValue.Substring(0, titleTagValue.IndexOf('#'));
}

Thanks again for the help!

What about HttpUtility's ParseQueryString() method?

http://msdn.microsoft.com/en-us/library/ms150046.aspx

--

Added sample with Jethro's suggestion:

var string1 = "?facets=All Groups||Brand&TitleTag=FOOBAR#back";
var pairs = HttpUtility.ParseQueryString(string1);

string titleTagValue = pairs["TitleTag"];

if (!string.IsNullOrEmpty(titleTagValue) && titleTagValue.IndexOf('#') > -1)
{
    titleTagValue = titleTagValue.Substring(0, titleTagValue.IndexOf('#'));
}

It looks like you are grabbing the page request querystring and adding it to the session container at some point. Instead of grabbing the whole querystring and putting it in the seesion couldn't you just grab the part of the querystring you need and save it to a specfic session key?

For instance:

Session["TitleTag"] = Request.QueryString["TitleTag"]

Then you can reference Session["TitleTag"] when you need it. This way you don't have to parse the string and the data contained in the session is more self describing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM