ASP.NET页面对象 - Request

来源:互联网 发布:贝叶斯分类算法步骤 编辑:程序博客网 时间:2024/05/09 17:04

   获取请求的页的 HttpRequest 对象。

一、HttpRequest

使 ASP.NET 能够读取客户端在 Web 请求期间发送的 HTTP 值。

      下面的代码示例使用 StreamWriter 类将若干 HttpRequest 类属性值的值写入文件。对于是字符串类型的属性,属性值被写入文件时将被编码为 HTML。表示集合的属性会被依次通过,而这些属性包含的各个键/值对都会被写入该文件。

<%@ Page Language="C#" %>

<%@ import Namespace="System.Threading" %>

<%@ import Namespace="System.IO" %>

<script runat="server">

 

    /* NOTE: To use this sample, create a c:/temp/CS folder,

    *  add the ASP.NET account (in IIS 5.x <machinename>/ASPNET,

    *  in IIS 6.x NETWORK SERVICE), and give it write permissions

    *  to the folder.*/

 

    private const string INFO_DIR = @"c:/temp/CS/RequestDetails";

    public static int requestCount;

 

    private void Page_Load(object sender, System.EventArgs e)

    {

 

        // Create a variable to use when iterating

        // through the UserLanguages property.

        int langCount;

 

        int requestNumber = Interlocked.Increment(ref requestCount);

 

        // Create the file to contain information about the request.

        string strFilePath = INFO_DIR + requestNumber.ToString() + @".txt";

 

 

        StreamWriter sw = File.CreateText(strFilePath);

 

        try

        {

            // Write request information to the file with HTML encoding.

            sw.WriteLine(Server.HtmlEncode(DateTime.Now.ToString()));

            sw.WriteLine(Server.HtmlEncode(Request.CurrentExecutionFilePath));

            sw.WriteLine(Server.HtmlEncode(Request.ApplicationPath));

            sw.WriteLine(Server.HtmlEncode(Request.FilePath));

            sw.WriteLine(Server.HtmlEncode(Request.Path));

 

            // Iterate through the Form collection and write

            // the values to the file with HTML encoding.

            // String[] formArray = Request.Form.AllKeys;

            foreach (string s in Request.Form)

            {

                sw.WriteLine("Form: " + Server.HtmlEncode(s));

            }

 

            // Write the PathInfo property value

            // or a string if it is empty.

            if (Request.PathInfo == String.Empty)

            {

                sw.WriteLine("The PathInfo property contains no information.");

            }

            else

            {

                sw.WriteLine(Server.HtmlEncode(Request.PathInfo));

            }

 

            // Write request information to the file with HTML encoding.

            sw.WriteLine(Server.HtmlEncode(Request.PhysicalApplicationPath));

            sw.WriteLine(Server.HtmlEncode(Request.PhysicalPath));

            sw.WriteLine(Server.HtmlEncode(Request.RawUrl));

 

            // Write a message to the file dependent upon

            // the value of the TotalBytes property.

            if (Request.TotalBytes > 1000)

            {

                sw.WriteLine("The request is 1KB or greater");

            }

            else

            {

                sw.WriteLine("The request is less than 1KB");

            }

 

            // Write request information to the file with HTML encoding.

            sw.WriteLine(Server.HtmlEncode(Request.RequestType));

            sw.WriteLine(Server.HtmlEncode(Request.UserHostAddress));

            sw.WriteLine(Server.HtmlEncode(Request.UserHostName));

            sw.WriteLine(Server.HtmlEncode(Request.HttpMethod));

 

            // Iterate through the UserLanguages collection and

            // write its HTML encoded values to the file.

            for (langCount=0; langCount < Request.UserLanguages.Length; langCount++)

            {

                sw.WriteLine(@"User Language " + langCount +": " + Server.HtmlEncode(Request.UserLanguages[langCount]));

            }

       }

 

       finally

       {

            // Close the stream to the file.

            sw.Close();

       }

 

        lblInfoSent.Text = "Information about this request has been sent to a file.";

    }

 

 

    private void btnSendInfo_Click(object sender, System.EventArgs e)

    {

        lblInfoSent.Text = "Hello, " + Server.HtmlEncode(txtBoxName.Text) +

          ". You have created a new  request info file.";

    }

 

</script>

<html>

<head>

</head>

<body>

    <form runat="server">

        <p>

        </p>

        <p>

            Enter your hame here:

            <asp:TextBox id="txtBoxName" runat="server"></asp:TextBox>

        </p>

        <p>

            <asp:Button id="btnSendInfo" onclick="btnSendInfo_Click" runat="server" Text="Click Here"></asp:Button>

        </p>

        <p>

            <asp:Label id="lblInfoSent" runat="server"></asp:Label>

        </p>

    </form>

</body>

</html>

 

二、HttpRequest 成员

公共构造函数

名称

说明

HttpRequest

初始化 HttpRequest 对象。

 公共属性

名称

说明

AcceptTypes

获取客户端支持的 MIME 接受类型的字符串数组。

AnonymousID

获取该用户的匿名标识符(如果存在)。

ApplicationPath

获取服务器上 ASP.NET 应用程序的虚拟应用程序根路径。

AppRelativeCurrentExecutionFilePath

获取应用程序根的虚拟路径,并通过对应用程序根使用波形符 (~) 表示法(例如,以“~/page.aspx”的形式)使该路径成为相对路径。

Browser

获取或设置有关正在请求的客户端的浏览器功能的信息。

ClientCertificate

获取当前请求的客户端安全证书。

ContentEncoding

获取或设置实体主体的字符集。

ContentLength

指定客户端发送的内容长度(以字节计)。

ContentType

获取或设置传入请求的 MIME 内容类型。

Cookies

获取客户端发送的 cookie 的集合。

CurrentExecutionFilePath

获取当前请求的虚拟路径。

FilePath

获取当前请求的虚拟路径。

Files

获取采用多部分 MIME 格式的由客户端上载的文件的集合。

Filter

获取或设置在读取当前输入流时要使用的筛选器。

Form

获取窗体变量集合。

Headers

获取 HTTP 头集合。

HttpMethod

获取客户端使用的 HTTP 数据传输方法(如 GETPOST HEAD)。

InputStream

获取传入的 HTTP 实体主体的内容。

IsAuthenticated

获取一个值,该值指示是否验证了请求。

IsLocal

获取一个值,该值指示该请求是否来自本地计算机。

IsSecureConnection

获取一个值,该值指示 HTTP 连接是否使用安全套接字(即 HTTPS)。

Item

CookiesFormQueryString ServerVariables 集合中获取指定的对象。

LogonUserIdentity

获取当前用户的 WindowsIdentity 类型。

Params

获取 QueryStringFormServerVariables Cookies 项的组合集合。

Path

获取当前请求的虚拟路径。

PathInfo

获取具有 URL 扩展名的资源的附加路径信息。

PhysicalApplicationPath

获取当前正在执行的服务器应用程序的根目录的物理文件系统路径。

PhysicalPath

获取与请求的 URL 相对应的物理文件系统路径。

QueryString

获取 HTTP 查询字符串变量集合。

RawUrl

获取当前请求的原始 URL

RequestType

获取或设置客户端使用的 HTTP 数据传输方法(GET POST)。

ServerVariables

获取 Web 服务器变量的集合。

TotalBytes

获取当前输入流中的字节数。

Url

获取有关当前请求的 URL 的信息。

UrlReferrer

获取有关客户端上次请求的 URL 的信息,该请求链接到当前的 URL

UserAgent

获取客户端浏览器的原始用户代理信息。

UserHostAddress

获取远程客户端的 IP 主机地址。

UserHostName

获取远程客户端的 DNS 名称。

UserLanguages

获取客户端语言首选项的排序字符串数组。

 公共方法

名称

说明

BinaryRead

执行对当前输入流进行指定字节数的二进制读取。

Equals 

已重载。 确定两个 Object 实例是否相等。 (从 Object 继承。)

GetHashCode 

用作特定类型的哈希函数。GetHashCode 适合在哈希算法和数据结构(如哈希表)中使用。 (从 Object 继承。)

GetType 

获取当前实例的 Type (从 Object 继承。)

MapImageCoordinates

将传入图像字段窗体参数映射为适当的 x 坐标值和 y 坐标值。

MapPath

已重载。 为当前请求将请求的 URL 中的虚拟路径映射到服务器上的物理路径。

ReferenceEquals 

确定指定的 Object 实例是否是相同的实例。 (从 Object 继承。)

SaveAs

HTTP 请求保存到磁盘。

ToString 

返回表示当前 Object String (从 Object 继承。)

ValidateInput

对通过 Cookies Form QueryString 属性访问的集合进行验证。

 受保护的方法

名称

说明

Finalize 

允许 Object 垃圾回收回收 Object 之前尝试释放资源并执行其他清理操作。 (从 Object 继承。)

MemberwiseClone 

创建当前 Object 的浅表副本。 (从 Object 继承。)

 

三、Request对象三种取得数据的方法

Request对象功能是从客户端得到数据,常用的三种取得数据的方法是:Request.FormRequest.QueryStringRequest。其第三种是前两种的一个缩写,可以取代前两种情况。而前两种主要对应的Form提交时的两种不同的提交方法:分别是Post方法和Get方法。

Request 对象的属性和方法比较多,常用的几个为:UserAgent 传回客户端浏览器的版本信息,UserHostAddress 传回远方客户端机器的主机IP 地址,UserHostName 传回远方客户端机器的DNS 名称,PhysicalApplicationPath 传回目前请求网页在Server 端的真实路径。

1、从浏览器获取数据

利用Request方法,可以读取其他页面提交过来的数据。提交的数据有两种形式:一种是通过Form表单提交过来,另一种是通过超级链接后面的参数提交过来,两种方式都可以利用Request对象读取。

<%@ Page Language="C#"%>

<%

    string strUserName = Request["Name"];

    string strUserLove = Request["Love"];

%>

姓名:<%=strUserName%>

爱好:<%=strUserLove%>

<form action="" method="post">

<P>姓名:<input type="TEXT" size="20" name="Name"></P>

<P>兴趣:<input type="TEXT" size="20" name="Love"></P>

<P><input type="submit" value=" "></P>

</form>

 

2、得到客户端的信息

利用Request对象内置的属性,可以得到一些客户端的信息,比如客户端浏览器版本和客户端地址等等

<%@ Page Language="C#"%>

客户端浏览器:<%=Request.UserAgent %>

客户端IP地址:<%=Request.UserHostAddress %>

当前文件服务端物理路径:<%=Request.PhysicalApplicationPath %>

 

四、Request对象包括:

 报头

 客户端的基本信息(如浏览器类型、版本号、用户所用的语言及编码方式等)

 请求方法(PostGet

 参数名

 参数值

 

Request对象的调用方法:

Request.Collection["Variable"]

其中,CollectionQueryStringFormCookiesServerVariables四种集合。Collection可以省略,如用Request["Variable"]调用,但这样会降低效率。

 

以下是这四种集合:

1QueryString集合

 QueryString集合收集的信息来自于请求Url中“?”号后面的数据,这些数据通常称为“Url附加信息”:

 http://www.aspcn.com/show.asp?id=111

 在此Url中,QueryString收集到的信息是“Show.asp?”后的附加数据“id=111

 此时,取得参数id的参数值的语句是:

 Request.QueryString["id"]

QueryString集合主要用于收集Http协议中的Get请求发送的数据,如果一个请求事件中被请求的程序Url中出现“?”号后的数据,则表示此次请求方式为Get。最常用的超链接,就是通过Get发送请求。也可以通过Form发送Get请求。

那么,在show.asp页面中,就可以用Request.QueryString["id"]获得id的参数值。

 

2Form集合

Form集合与QueryString类似,但它用于收集Post方法发送的请求数据(Get方法一般只能传递256字节的数据,而Post可以达到2M)。

Post请求必须由Form来发送。那么,在show.asp页面中,就可以用Request.Form["id"]获得id的参数值。

 

3Cookies集合

 

4ServerVariable集合

 ServerVariable(环境变量)集合中包含了服务器和客户端的系统信息。

 ---客户端:

 (1)获取客户端浏览器版本号: Request.ServerVariable["HTTP_USER_AGENT"]

 (2)获取客户端IP地址:  Request.ServerVariable["REMOTE_ADDR"]

 (3)获取客户端所使用的语言:  HTTP_ACCEPT_LANGUAGE

 (4)获取请求的方法:   REQUEST_METHOD

 (5)获取请求信息的内容的总符数:  CONTENT_LENGTH

 (6)获取请求信息的类型   CONTENT_TYPE

 (7)获取URL的附加信息:   QUERY_STRING

 (8)获取网关接口:   GATEWAY_INTERFACE

 ---服务器:

 (1)获取服务器的IP地址:  Request.ServerVariable["LOCAL_ADDR"]

 (2)获取服务器的主机名:  Request.ServerVariable["SERVER_NAME"]

 (3)获取当前执行程序的虚拟目录:   PATH_INFO

 (4)获取当前执行程序的绝对路径:   PATH_TRANSLATED

 (5)获取当前程序的文件名(包含虚拟路径): SCRIPT_NAME

 (6)获取服务器接受请求的端口:   SERVER_PORT

 (7)获取服务器遵从的协议及版本号:  SERVER_PROTOCAL

 

Browser对象

 ASP.netBrowser对象是通过调用RequestBrowser属性直接获得的,它可以获得浏览器的更深入的信息

 检测浏览器的类型:  Request.Brower.Brower 显示结果,例如 IE

 检测浏览器的版本:  Requet.Brower.Version 显示结果,例如 6.0b

 检测浏览器是否支持ActiveX控件:  ActiveXControls

 检测浏览器是否支持Cookies  Cookies

 检测浏览器是否支持VBScript  VBSCript

 

其它Request属性、方法:

 * FilePath 取得当前请求的文件路径,例: String filePath = Request.FilePath;

 * HttpMethod 取得当前请求的方法

 * Files

 * Params 获得 QueryString + Form + ServerVariable + Cookies 的集合。

 * TotalBytes 请求内容的大小

 * Url  获得Url信息,例:

    HttpUrl objUrl = Request.URL;

    string sPort = objUrl.Port;

    string sProtocol = objUrl.Protocol;

 * UserHostAddress(用户IP)、UserHostNameUserLanguages

 

五、Request获取url信息的各种方法比较

ASP.NET编程中经常需要用Request获取url的有关信息,Request中有多种方法获取url信息,但我经常忘了各种方法的具体作用,今天我就写了个测试程序,将各种方法得到的结果列出来,以后用时直接参考一下就行了。

测试的url地址是[url]http://www.test.com/testweb/default.aspx[/url], 结果如下:

 

Request.ApplicationPath: /testweb

 

Request.CurrentExecutionFilePath: /testweb/default.aspx

 

Request.FilePath: /testweb/default.aspx

 

Request.Path: /testweb/default.aspx

 

Request.PathInfo:

 

Request.PhysicalApplicationPath: E:/WWW/testweb/  获取当前正在执行的服务器应用程序的根目录的物理文件系统路径。

 

Request.PhysicalPath: E:/WWW/testweb/default.aspx

 

Request.RawUrl: /testweb/default.aspx

 

Request.Url.AbsolutePath: /testweb/default.aspx

 

Request.Url.AbsoluteUri: [url]http://www.test.com/testweb/default.aspx[/url]

 

Request.Url.Host: [url]www.test.com[/url]

 

Request.Url.LocalPath: /testweb/default.aspx

 

六、获取客户端信息

Response.Write("客户端计算机名:" + Request.UserHostName + "<BR />");  

Response.Write("客户端IP" + Request.UserHostAddress + "<BR />");  

Response.Write("浏览器:" + Request.Browser.Browser + "<BR />");  

Response.Write("浏览器版本:" + Request.Browser.Version + "<BR />");  

Response.Write("浏览器类型:" + Request.Browser.Type + "<BR />");  

Response.Write("客户端操作系统:" + Request.Browser.Platform + "<BR />");  

Response.Write("是否支持Java" + Request.Browser.JavaApplets + "<BR />");  

Response.Write("是否支持框架网页:" + Request.Browser.Frames + "<BR />");  

Response.Write("是否支持Cookie" + Request.Browser.Cookies + "<BR />");  

Response.Write("客户端.NET Framework版本:" + Request.Browser.ClrVersion + "<BR />");  

Response.Write("JScript版本:" + Request.Browser.JScriptVersion + "<BR />");  

 

Response.Write("请求的虚拟路径:" + Request.Path + "<BR />");  

//Response.Write("title" + Request.He + "<BR />");  

for(int i=0;i<Request.Headers.Count;i++){  

Response.Write(Request.Headers.Keys[i]+":"  + Request.Headers[Request.Headers.Keys[i]]+ "<BR />");  

}  

Response.Write("请求的物理路径:" + Request.PhysicalPath + "<BR />");  

 

Response.Write("浏览器类型和版本:" + Request.ServerVariables["HTTP_USER_AGENT"] + "<BR />");  

Response.Write("用户的IP地址:" + Request.ServerVariables["REMOTE_ADDR"] + "<BR />");  

Response.Write("请求的方法:" + Request.ServerVariables["REQUEST_METHOD"] + "<BR />");  

Response.Write("服务器的IP地址:" + Request.ServerVariables["LOCAL_ADDR"] + "<BR />"); 

原创粉丝点击