源码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Http_Head.aspx.cs" Inherits="Http_Head" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using System.Collections.Specialized;
public partial class Http_Head : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
NameValueCollection myHeader = new NameValueCollection();
int i;
string strKey;
myHeader = Request.Headers;
int total = myHeader.Count;
string strResult = "";
for (i = 1; i < total; i++)
{
strKey = myHeader.GetKey(i);
strResult += "<p>名字:" + strKey + "值:" + myHeader.Get(strKey)/* + myHeader.Get(i)*/ + "</p>";
}
Label1.Text = strResult;
}
}
运行结果:
名字:Accept值:*/*
名字:Accept-Encoding值:gzip, deflate
名字:Accept-Language值:zh-cn
名字:Host值:localhost:1673
名字:User-Agent值:Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)
名字:UA-CPU值:x86
最近在研究HttpRequest类,发现里面的很多属性都返回一个NameValueCollection对象,今天再来了解一下这个神秘的对象。
随便写了个例子,发现跟HashTable类似。但是这个东西有点怪,就是当存在一个key的时候,你在add的话,会追加进当前key中。而不是简单替换。
NameValueCollection nvc = new NameValueCollection(); nvc.Add("第一个", "刘德华"); nvc.Add("第二个", "张学友"); nvc.Add("第三个", "郭富城"); nvc.Add("第四个", "黎明"); foreach (string str in nvc) { Response.Write(str + ":" + nvc[str] + "; "); }
浏览器输出:
下面通过MSDN来详细了解下这个类。
一、共有属性
AllKeys 该属性可以获取NameValueCollection 中的所有键。返回一个字符串数组。
Count 该属性获取NameValueCollection包含键值对的数目,返回一个int。
Item 该属性表明NameValueCollection可以通过索引访问,如nvc[1],nvc["key"].
Keys 该属性获取 NameObjectCollectionBase.KeysCollection 实例,该实例包含 NameObjectCollectionBase 实例中的所有键。
二、受保护属性
IsReadOnly 获取或设置一个值,通过该值指示 NameObjectCollectionBase 实例是否为只读的。
三、方法
Add 将项添加到当前 NameValueCollection。例如:一个参数是将一个NameValueCollection复制到当前NameValueCollection,两个就是一个键值对。
Clear 使缓存数组无效,并清空NameValueCollection。
CopyTo 从目标数组的指定索引处开始将整个 NameValueCollection 复制到兼容的一维 Array。
Get 获取 NameValueCollection 中指定项的值,可以通过key或索引号访问。
GetEnumerator 返回循环访问 NameObjectCollectionBase 的枚举数。
GetKey 获取 NameValueCollection 的指定索引处的键。
GetValues 获取 NameValueCollection 中指定项的值。返回一个字符串数组,为什么要返回一个数组呢?因为一个值里面可能会包括多个项。
HasKeys 获取一个值,该值指示 NameValueCollection 是否包含非空引用的键。即有键值对且键不为null就返回true,否则返回false。可用于判断对象是否为空。
Remove 移除 NameObjectCollectionBase 实例中具有指定键的项。只能够根据键key移除项,不能用索引移除。
Set 根据键值对重新设置一个项目。Set("第一个","刘德华");
OnDeserialization 实现 ISerializable 接口,并在完成反序列化之后引发反序列化事件。