System.Net.Http.HttpResponseHeadersExtensions.AddCookies C# (CSharp) Method

AddCookies() public static method

Adds cookies to a response. Each Set-Cookie header is represented as one CookieHeaderValue instance. A CookieHeaderValue contains information about the domain, path, and other cookie information as well as one or more CookieState instances. Each CookieState instance contains a cookie name and whatever cookie state is associate with that name. The state is in the form of a System.Collections.Specialized.NameValueCollection which on the wire is encoded as HTML Form URL-encoded data. This representation allows for multiple related "cookies" to be carried within the same Cookie header while still providing separation between each cookie state. A sample Cookie header is shown below. In this example, there are two CookieState with names state1 and state2 respectively. Further, each cookie state contains two name/value pairs (name1/value1 and name2/value2) and (name3/value3 and name4/value4). Set-Cookie: state1:name1=value1&name2=value2; state2:name3=value3&name4=value4; domain=domain1; path=path1;
public static AddCookies ( this headers, IEnumerable cookies ) : void
headers this The response headers
cookies IEnumerable The cookie values to add to the response.
return void
        public static void AddCookies(this HttpResponseHeaders headers, IEnumerable<CookieHeaderValue> cookies)
        {
            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }

            if (cookies == null)
            {
                throw new ArgumentNullException("cookies");
            }

            foreach (CookieHeaderValue cookie in cookies)
            {
                if (cookie == null)
                {
                    continue; // Good thing this code aint staying around...
                }

                headers.AddWithoutValidation(SetCookie, cookie.ToString());
            }
        }

Usage Example

コード例 #1
0
        public void AddCookies_ThrowsOnNull()
        {
            HttpResponseHeaders      headers = CreateHttpResponseHeaders();
            List <CookieHeaderValue> cookies = new List <CookieHeaderValue>();

            Assert.ThrowsArgumentNull(() => HttpResponseHeadersExtensions.AddCookies(null, cookies), "headers");
            Assert.ThrowsArgumentNull(() => HttpResponseHeadersExtensions.AddCookies(headers, null), "cookies");
        }
HttpResponseHeadersExtensions