NameValueCollection 集合用法

      此集合基于 NameObjectCollectionBase 类。但与 NameObjectCollectionBase 不同,该类在一个键下存储多个字符串值。该类可用于标头、查询字符串和窗体数据。

    using System.Collections.Specialized  

    int loop1, loop2;
    NameValueCollection coll;

    // Load ServerVariable collection into NameValueCollection object.
    coll=Request.ServerVariables;
    // Get names of all keys into a string array.
    String[] arr1 = coll.AllKeys;
    for (loop1 = 0; loop1 < arr1.Length; loop1++)
    {
        Response.Write("Key: " + arr1[loop1] + "<br>");
        String[] arr2=coll.GetValues(arr1[loop1]);
        for (loop2 = 0; loop2 < arr2.Length; loop2++)
        {
            Response.Write("Value " + loop2 + ": " + arr2[loop2] + "<br>");
        }
    }

      Request(item) 在 ASP 中,此方法返回字符串数组。在 ASP .NET 中,它返回 NameValueCollection。
      Request.QueryString(item) 在 ASP 中,此方法返回字符串数组。在 ASP .NET 中,它返回 NameValueCollection。
       Request.Form(item) 在 ASP 中,此方法返回字符串数组。在 ASP .NET 中,它返回 NameValueCollection。
正如您所见,对于涉及到的所有方法,其变化基本上都相同。
       如果访问的 item(项)只包含特定关键字的一个值,您将不必修改自己的代码。但是,如果给定的关键字具有多个值,您将需要使用其它方法返回值的集合。另请注意,Visual Basic .NET 中的集合都是基于 0,而 VBScript 中的集合是基于 1 的。
       例如,在 ASP 中,将按下列方式访问 http://localhost/myweb/valuetest.asp?values=10&values=20 请求返回的各个查询字符串值:

       在 ASP .NET 中,QueryString 属性返回 NameValueCollection 对象,在检索所需的实际项之前,将需要从该对象中检索 Values 集合。另外需要注意,集合中的第一项是使用 0 而非 1 索引进行检索的:

下列代码在 ASP 和 ASP .NET 中的运行结果相同:
   <%
         '输出“10”和“20”
         Response.Write (Request.QueryString("values"))
   %>

AllKeys属性,取得所有关键字名称。

====以下是一个取得IP和操作系统以及浏览器的例子=========

    private string getIp()
    {
        /*穿过代理服务器取远程用户真实IP地址:*/
        if(Request.ServerVariables["HTTP_VIA"]!=null)
        return Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        else
        return Request.ServerVariables["REMOTE_ADDR"].ToString();
    }
    Label2.Text =getIp();
    HttpBrowserCapabilities bc = new HttpBrowserCapabilities();
    bc = Request.Browser;
    string xitong ="你的操作系统为";
    Label3.Text=xitong+bc.Platform + " 浏览器类型:" + bc.Type;

原文地址:https://www.cnblogs.com/fhuafeng/p/1786936.html