申請(qǐng)免費(fèi)試用、咨詢(xún)電話(huà):400-8352-114
AMTeam.org
從Web
Services中訪(fǎng)問(wèn)服務(wù)器變量
在新聞組中最經(jīng)常被問(wèn)到的問(wèn)題就是“如何從一個(gè)web Services(Web服務(wù))內(nèi)部獲取客戶(hù)瀏覽器的IP地址?”
這個(gè)問(wèn)題的答案非常簡(jiǎn)單。system.web.services名稱(chēng)空間內(nèi)部的Context類(lèi)代表了web服務(wù)的上下文。換句話(huà)說(shuō),它從一個(gè)正在運(yùn)行的web服務(wù)內(nèi)部對(duì)不同的對(duì)象進(jìn)行引用。比如Response(響應(yīng))、Request(請(qǐng)求)和Session對(duì)象,以及在服務(wù)上調(diào)試是否激活之類(lèi)的信息。
本文我們用一個(gè)非?;镜睦觼?lái)描述兩件事:
1、取得客戶(hù)瀏覽器的IP地址
2、取得所有的web 服務(wù)器變量
源代碼如下,很容易理解:
<%@ Webservice Language="C#" class="httpvars"
%>
using System;
using System.Collections;
using
System.Web.Services;
public class httpvars :
WebService
{
// This method returns the IP address of the
client
[WebMethod]
public String ipAddress ()
{
//
The Context object contains reference to Request object
return
Context.Request.ServerVariables["REMOTE_ADDR"];
}
// This method
returns the all the server variables as HTML
[WebMethod]
public
String allHttpVars ()
{
// Instantiate a collection that will hold
the
// key-value collection of server
variables
NameValueCollection serverVars;
String returnValue =
"";
serverVars = Context.Request.ServerVariables;
// Retrieve all
the Keys from server variables collection
// as a string
array
String[] arVars = serverVars.AllKeys;
// Loop through the
keys array and obtain the
// values corresponding to the individual
keys
for (int x = 0; x < arVars.Length;
x++)
{
returnValue+= "<b>" + arVars[x] + "</b>:
";
returnValue+= serverVars[arVars[x]] +
"<br>";
}
return returnValue;
}
}
http://www.dotnet101.com/articles/demo/art033_servervars.asmx進(jìn)行代碼演示。注意:第二個(gè)方法allHttpVars()返回HTML內(nèi)容。
|