tangol100
tangol100

Reputation: 21

Convert HttpCookieCollection to NameValueCollection

My objective is to store all request(*QueryString,Form,Headers,Cookies*) information to a single NameValueCollection.

Here is my code so far

var mainNVC = new NameValueCollection();
mainNVC.Add(context.Request.Form); //works
mainNVC.Add(context.Request.Headers); //works
mainNVC.Add(context.Request.QueryString); //works
mainNVC.Add(context.Request.Cookies); // error: Argument 1: cannot convert from 'System.Web.HttpCookieCollection' to 'System.Collections.Specialized.NameValueCollection'

Tried using Request.Param however, I don't want the server variables to be included.

Upvotes: 2

Views: 2258

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149588

This doesn't work because Request.Cookies is of type HttpCookieCollection. You'll need to convert it to a NameValueCollection.

You can create an extension method called ToNameValueCollection():

public static class CookieCollectionExtensions
{
    public static NameValueCollection ToNameValueCollection(
          this HttpCookieCollection cookieCollection)
    {
        var nvc = new NameValueCollection();
        foreach (var key in cookieCollection.AllKeys)
        {
            nvc.Add(key, cookieCollection[key].Value);
        }

        return nvc;
    }
}

And then when you add the Cookies:

mainNVC.Add(context.Request.Cookies.ToNameValueCollection());

Upvotes: 4

Related Questions