2

我的目标是将所有request(*QueryString,Form,Headers,Cookies*)信息存储到一个NameValueCollection.

到目前为止,这是我的代码

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'

但是尝试使用Request.Param,我不希望包含服务器变量。

4

1 回答 1

4

这不起作用,因为Request.Cookies它是 type HttpCookieCollection。您需要将其转换为NameValueCollection.

您可以创建一个名为的扩展方法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;
    }
}

然后当你添加Cookies

mainNVC.Add(context.Request.Cookies.ToNameValueCollection());
于 2015-01-09T08:14:20.043 回答