0

I need to send more than a Set-Cookie HTTP header using HttpWebRequest class.

Problem is first request.Headers.Add("Set-Cookie", "[cookie string]") adds the header as expected, but subsequent ones are concatenated in the first added header.

Default behavior complicates obtaning a set of cookies by the receiver of a given request, because isn't that easy split the header again in separate cookies' strings.

Is there any way of adding n times some header?

Perhaps some headers mustn't be repeated, but Set-Cookie is a valid use case, because receiver should read more than a cookie.

Thank you.

1 Answer 1

1

After spending some time looking for an out-of-the-box solution, I ended implementing an extension method to 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);
    }
}

Thanks to this wonderful extension method, I'm able to convert headers' collection to a lookup, which allows duplicate keys, and at the end of the day, doing some processing, I get a list of all HTTP headers in separately:

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

I hope sharing my solution will be a good contribution, as I guess others had or are having a similar case use!

Sign up to request clarification or add additional context in comments.

1 Comment

If it comes to cookies, I believe that HttpWebRequest.CookieContainer property is what you were looking for, some more reading here: msdn.microsoft.com/en-us/library/dd920298(v=vs.95).aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.