一个好用的C# HttpCookieHelper.cs类

 1  using System;  
 2 using System.Collections.Generic;  
 3 using System.Text;  
 4 using System.Text.RegularExpressions;  
 5   
 6 namespace DotNet.Utilities  
 7 {  
 8      /// <summary>  
 9     /// Cookie操作帮助类  
10     /// </summary>  
11     public static class HttpCookieHelper  
12     {  
13         /// <summary>  
14         /// 根据字符生成Cookie列表  
15         /// </summary>  
16         /// <param name="cookie">Cookie字符串</param>  
17         /// <returns></returns>  
18         public static List<CookieItem> GetCookieList(string cookie)  
19         {  
20             List<CookieItem> cookielist = new List<CookieItem>();  
21             foreach (string item in cookie.Split(new string[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries))  
22             {  
23                 if (Regex.IsMatch(item, @"([\s\S]*?)=([\s\S]*?)$"))  
24                 {  
25                     Match m = Regex.Match(item, @"([\s\S]*?)=([\s\S]*?)$");  
26                     cookielist.Add(new CookieItem() { Key = m.Groups[1].Value, Value = m.Groups[2].Value });  
27                 }  
28             }  
29             return cookielist;  
30         }  
31   
32         /// <summary>  
33         /// 根据Key值得到Cookie值,Key不区分大小写  
34         /// </summary>  
35         /// <param name="Key">key</param>  
36         /// <param name="cookie">字符串Cookie</param>  
37         /// <returns></returns>  
38         public static string GetCookieValue(string Key, string cookie)  
39         {  
40             foreach (CookieItem item in GetCookieList(cookie))  
41             {  
42                 if (item.Key == Key)  
43                     return item.Value;  
44             }  
45             return "";  
46         }  
47         /// <summary>  
48         /// 格式化Cookie为标准格式  
49         /// </summary>  
50         /// <param name="key">Key值</param>  
51         /// <param name="value">Value值</param>  
52         /// <returns></returns>  
53         public static string CookieFormat(string key, string value)  
54         {  
55             return string.Format("{0}={1};", key, value);  
56         }  
57     }  
58   
59     /// <summary>  
60     /// Cookie对象  
61     /// </summary>  
62     public class CookieItem  
63     {  
64         /// <summary>  
65         ///66         /// </summary>  
67         public string Key { get; set; }  
68         /// <summary>  
69         ///70         /// </summary>  
71         public string Value { get; set; }  
72     }  
73 }  

 

转载于:https://www.cnblogs.com/sanler/p/7249203.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值