vb.net 如何从 set-cookie 标头解析名称-值对?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15578634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I parse name-value pairs from the set-cookie header?
提问by Brent
I'm looking for a clean way to parse out 2 variables from the the set-cookie header in an httpwebrequest object.
我正在寻找一种干净的方法来从 httpwebrequest 对象的 set-cookie 标头中解析出 2 个变量。
The string in the Set-Cookie header is as follows:
Set-Cookie 头中的字符串如下:
X-Mapping-dmogknml=6652DD088AB10EE6A65DD9C700872364;
path=/,ASP.NET_SessionId=f4jg1h55eoqbdk452blsozfl; path=/;
HttpOnly,id=111,status=rejected; expires=Thu, 21-Mar-2013 07:31:55 GMT; path=/,statusDes=
Validation Failed ; expires=Thu, 21-Mar-2013 07:31:55 GMT; path=/,X-Mapping
dmogknml=dmogknml=6652DD088AB10EE6A65DD9C700872; path=/
I basically want to parse out "rejected" from "status=rejected" and "validation failed" from "statusDes=Validation Failed" into 2 string variables. I've worked out 2 solutions in my head but they seem kinda clunky:
我基本上想将“status=rejected”中的“rejected”和“statusDes=Validation Failed”中的“validation failed”解析为2个字符串变量。我在脑海中想出了 2 个解决方案,但它们看起来有点笨拙:
- Looping and Splitting on ";", then split on ",", then split on "=".
- Using substring.
- 在“;”上循环和拆分,然后在“,”上拆分,然后在“=”上拆分。
- 使用子串。
Please advise.
请指教。
采纳答案by Oded
You can use the overload of Splitthat takes a collection of Char.
您可以使用 的重载Split需要一个集合Char。
var values = theCookie.Split(new [] {';', ',', '='},
StringSplitOptions.RemoveEmptyEntries);
You can then loop through the valuestwo at a time, looking for the keys to fetch the values, or you can convert to a dictionary first (using LINQ ToDictionary).
然后,您可以values一次遍历两个,查找键以获取值,或者您可以先转换为字典(使用 LINQ ToDictionary)。
回答by John Bustos
Try using Regular Expressions.
尝试使用正则表达式。
This should do it (VB code):
这应该这样做(VB代码):
Dim Pattern As String = "status=(?<Status>.*?);.*?statusDes=(?<StatusDes>.*?);"
Dim m As Match = Regex.Match(input:=MyData, pattern:=Pattern , options:=RegexOptions.IgnoreCase + RegexOptions.Singleline)
Dim Status as String
Dim StatusDes as String
Status = m.Groups("Status").ToString
StatusDes = m.Groups("StatusDes").ToString
Remember to import Imports System.Text.RegularExpressions
记得导入 Imports System.Text.RegularExpressions
Hope tihs helps!
希望有帮助!

