获取系统变量在.net 的web应用程序中的确是非常方便,比如获取 "http://ap2:8080/"或者"http://10.0.0.1/mypplication/"等诸如此类的系统变量。
注:本文主要是针对.net Framework 1.0、1.1的情况,因为.net 2.0的命名空间已经发生了很大的变化,在后面的文章中将会专门加以介绍

为描述方便,先新建一aspx文件,前台文件如下:

web程序中获取应用程序系统变量的方法( For.net 1.1)<body MS_POSITIONING="GridLayout">
web程序中获取应用程序系统变量的方法( For.net 1.1)        
<form id="Form2" method="post" runat="server">
web程序中获取应用程序系统变量的方法( For.net 1.1)            
<FONT face="宋体">
web程序中获取应用程序系统变量的方法( For.net 1.1)                
<asp:Button id="btn_Page" style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 16px" runat="server"
web程序中获取应用程序系统变量的方法( For.net 1.1)                    Text
="通过Page获取"></asp:Button>
web程序中获取应用程序系统变量的方法( For.net 1.1)                
<asp:Label id="lbInfo1" style="Z-INDEX: 102; LEFT: 48px; POSITION: absolute; TOP: 56px" runat="server"></asp:Label>
web程序中获取应用程序系统变量的方法( For.net 1.1)                
<asp:Button id="btn_ServerVal" style="Z-INDEX: 103; LEFT: 520px; POSITION: absolute; TOP: 16px"
web程序中获取应用程序系统变量的方法( For.net 1.1)                    runat
="server" Text="通过ServerVariables获取"></asp:Button>
web程序中获取应用程序系统变量的方法( For.net 1.1)                
<asp:Label id="lbInfo2" style="Z-INDEX: 104; LEFT: 48px; POSITION: absolute; TOP: 80px" runat="server"></asp:Label>
web程序中获取应用程序系统变量的方法( For.net 1.1)                
<asp:Label id="lbInfo3" style="Z-INDEX: 105; LEFT: 48px; POSITION: absolute; TOP: 104px" runat="server"></asp:Label>
web程序中获取应用程序系统变量的方法( For.net 1.1)                
<asp:Button id="btn_Cintext" style="Z-INDEX: 106; LEFT: 280px; POSITION: absolute; TOP: 16px"
web程序中获取应用程序系统变量的方法( For.net 1.1)                    runat
="server" Text="通过Context获取"></asp:Button></FONT>
web程序中获取应用程序系统变量的方法( For.net 1.1)        
</form>
web程序中获取应用程序系统变量的方法( For.net 1.1)    
</body>



第一种方法,直接在在页面中获取。利用Page.Request命名空间。

web程序中获取应用程序系统变量的方法( For.net 1.1)private void btn_Page_Click(object sender, System.EventArgs e)

第二种方法:在非Web项目中用Context的Request方法。

web程序中获取应用程序系统变量的方法( For.net 1.1)private void btn_Cintext_Click(object sender, System.EventArgs e)
        }


第三种方法:可以从Request.ServerVariables的集合中获取 。获取的变量也最全。

web程序中获取应用程序系统变量的方法( For.net 1.1)private void btn_ServerVal_Click(object sender, System.EventArgs e)
        }

亦可用于 Web service

注意,以上方法获取IP未必真实。

相关文章: