Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 多次添加HTTP头并使用HttpWebRequest单独发送_Asp.net_.net_Http_Cookies_.net 4.0 - Fatal编程技术网

Asp.net 多次添加HTTP头并使用HttpWebRequest单独发送

Asp.net 多次添加HTTP头并使用HttpWebRequest单独发送,asp.net,.net,http,cookies,.net-4.0,Asp.net,.net,Http,Cookies,.net 4.0,我需要使用HttpWebRequest类发送多个Set CookieHTTP头 问题是第一个request.Headers.Add(“Set Cookie”,“[Cookie string]”)按预期添加头,但随后的头会连接到第一个添加的头中 默认行为使给定请求的接收者获取一组cookie变得复杂,因为在单独的cookie字符串中再次拆分头不是那么容易 有没有办法将某个标题添加n次? 也许有些标题不能重复,但Set Cookie是一个有效的用例,因为接收者应该读取比Cookie更多的内容 谢谢。

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

问题是第一个
request.Headers.Add(“Set Cookie”,“[Cookie string]”)
按预期添加头,但随后的头会连接到第一个添加的头中

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

有没有办法将某个标题添加n次?

也许有些标题不能重复,但
Set Cookie
是一个有效的用例,因为接收者应该读取比Cookie更多的内容


谢谢。

在花了一些时间寻找现成的解决方案后,我结束了对
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);
    }
}

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

如果涉及到cookies,我相信HttpWebRequest.CookieContainer属性就是您所寻找的,请在此阅读更多内容:
string wholeCookie = WebOperationContext.Current.IncomingRequest.Headers.ToLookup()["Set-Cookie"].Single(cookie => cookie.Contains("[Cookie name]"));