简体   繁体   English

如何使用 C# 从类似 QueryString 的字符串中提取值

[英]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.我有一个 ASP.NET 页面,该页面的值存储在 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?以下面的字符串为例——从这个字符串中获取“FOOBAR”的最佳方法是什么? 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.感谢 jglouie 提出使用“ParseQueryString”的想法——最终成功了。 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? HttpUtility 的 ParseQueryString() 方法呢?

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

-- --

Added sample with Jethro's suggestion:添加了 Jethro 建议的示例:

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.看起来您正在获取页面请求查询字符串并将其添加到 session 容器中。 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?除了获取整个查询字符串并将其放入查看中,您难道不能只获取您需要的查询字符串部分并将其保存到特定的 session 键吗?

For instance:例如:

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

Then you can reference Session["TitleTag"] when you need it.然后您可以在需要时引用 Session["TitleTag"] 。 This way you don't have to parse the string and the data contained in the session is more self describing.这样您就不必解析字符串,并且 session 中包含的数据更具自我描述性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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