
2.6 Server对象

视频讲解
2.6.1 Server对象概述
Server对象定义了一个与Web服务器相关的类,提供对服务器上的方法和属性的访问,用于访问服务器上的资源。
2.6.2 Server对象的常用属性和方法
Server对象的常用属性及说明如表2.16所示。
表2.16 Server对象的常用属性及说明

Server对象的常用方法及说明如表2.17所示。
表2.17 Server对象的常用方法及说明

2.6.3 使用Server.Execute方法和Server.Transfer方法重定向页面
Execute方法用于将执行从当前页面转移到另一个页面,并将执行返回到当前页面。执行所转移的页面在同一浏览器窗口中执行,然后原始页面继续执行。故执行Execute方法后,原始页面保留控制权。
而Transfer方法用于将执行完全转移到指定页面。与Execute方法不同,执行该方法时主调页面将失去控制权。
【例2.10】重定向页面。(示例位置:mr\TM\02\10)
下面的示例实现的主要功能是通过Server对象的Execute方法和Transfer方法重定向页面。执行程序,单击“Execute方法”按钮,示例运行结果如图2.11所示;单击“Transfer方法”按钮,示例运行结果如图2.12所示。

图2.11 单击“Execute方法”按钮示例运行结果

图2.12 单击“Transfer方法”按钮示例运行结果
程序实现的主要步骤如下。
(1)新建一个网站,默认主页为Default.aspx,在Default.aspx页面上添加2个Button控件,它们的属性设置如表2.18所示。
表2.18 Default.aspx页面中控件的属性设置及用途

(2)单击“Execute方法”按钮,利用Server对象的Execute方法从Default.aspx页重定向到newPage.aspx页,然后控制权返回到主调页面(Default.aspx)并执行其他操作。代码如下:

(3)单击“Transfer方法”按钮,利用Server对象的Transfer方法从Default.aspx页重定向到newPage.aspx页,控制权完全转移到newPage.aspx页。代码如下:

2.6.4 使用Server.MapPath方法获取服务器的物理地址
MapPath方法用来返回与Web服务器上的指定虚拟路径相对应的物理文件路径。语法如下:

其中,path表示Web服务器上的虚拟路径,如果path值为空,则该方法返回包含当前应用程序的完整物理路径。例如,下面的示例是在浏览器中输出指定文件Default.aspx的物理文件路径。

技巧
可以使用Server.MapPath(".")获取当前目录所在服务器的物理路径。
2.6.5 使用Server.UrlEncode方法对字符串进行编码
Server对象的UrlEncode方法用于对通过URL传递到服务器的数据进行编码。语法如下:

其中,string为需要进行编码的数据。例如:

编码后的输出结果为:http%3a%2f%2fDefault.aspx。
Server对象的UrlEncode方法的编码规则如下:
- ☑ 空格将被加号“+”字符所代替。
- ☑ 字段不被编码。
- ☑ 字段名将被指定为关联的字段值。
- ☑ 非ASCII字符将被转义码所替代。
2.6.6 使用Server.UrlDecode方法对字符串进行解码
UrlDecode方法用来对字符串进行URL解码并返回已解码的字符串。例如:

解码后的输出结果为http://Default.aspx。
技巧
如何解决Response.Redirec方法传递汉字丢失或乱码问题?
使用Response.Redirec方法传递汉字时,有时会发现传递的内容与接收的内容不一致,接收到的值丢失了几个字或乱码。怎样才能解决呢?
为了确保传递的汉字可以被正确地接收,可以在传值之前使用Server对象的UrlEncode方法对所传递的汉字进行URL编码。代码如下:

接收值时,使用Server对象的UrlDecode方法对所接收的汉字进行URL解码。代码如下:
