【问题标题】:Add an HTTP header more than once and send it separately using HttpWebRequest多次添加 HTTP 标头并使用 HttpWebRequest 单独发送
【发布时间】:2011-12-13 21:38:54
【问题描述】:

我需要使用HttpWebRequest 类发送多个Set-Cookie HTTP 标头。

问题首先是request.Headers.Add("Set-Cookie", "[cookie string]") 按预期添加了标头,但后续的在第一个添加的标头中连接。

默认行为使给定请求的接收者获取一组 cookie 变得复杂,因为在单独的 cookie 字符串中再次拆分标头并不容易。

有什么方法可以添加 n 次标头吗?

也许某些标头不能重复,但Set-Cookie 是一个有效的用例,因为接收者应该读取的不仅仅是 cookie。

谢谢。

【问题讨论】:

    标签: asp.net .net http cookies .net-4.0


    【解决方案1】:

    在花了一些时间寻找开箱即用的解决方案后,我结束了对System.Net.WebHeaderCollection 的扩展方法:

    public static class WebHeaderCollectionExtensions
    {
        public static ILookup<string, string> ToLookup(this WebHeaderCollection some)
        {
            List<KeyValuePair<string, string>> headers = new List<KeyValuePair<string, string>>();
    
            if (some.Count > 0)
            {
                string[] tempSplittedHeaders = null;
    
                foreach (string headerName in some)
                {
                    if (some[headerName].Contains(";,"))
                    {
                        tempSplittedHeaders = Regex.Split(some[headerName], ";,");
    
                        foreach (string splittedHeader in tempSplittedHeaders)
                        {
                            headers.Add(new KeyValuePair<string, string>(headerName, splittedHeader));
                        }
                    }
                    else
                    {
                        headers.Add(new KeyValuePair<string, string>(headerName, some[headerName]));
                    }
                }
            }
    
            return headers.ToLookup(keySelector => keySelector.Key, elementSelector => elementSelector.Value);
        }
    }
    

    感谢这个奇妙的扩展方法,我能够将标头的集合转换为允许重复键的查找,并且在一天结束时,进行一些处理,我分别获得了所有 HTTP 标头的列表:

    string wholeCookie = WebOperationContext.Current.IncomingRequest.Headers.ToLookup()["Set-Cookie"].Single(cookie => cookie.Contains("[Cookie name]"));
    

    我希望分享我的解决方案将是一个很好的贡献,因为我猜其他人已经或正在使用类似的案例!

    【讨论】:

    猜你喜欢
    • 2012-01-28
    • 2012-04-08
    • 1970-01-01
    • 2012-01-09
    • 2017-12-30
    • 1970-01-01
    • 2014-09-20
    相关资源
    最近更新 更多