HttpRequest Request

  • 7871
  • 0
  • 2018-03-09

關於 HttpRequest Request的一些操作跟屬性紀錄

要判斷是post還是get的方式呼叫,可以直接使用 : Request.IsPostBack

或是判斷Request.HttpMethod 

protected void Page_Load(object sender, EventArgs e)
{
	string requestMethod = Request.HttpMethod;
	string remoteIP = Request.ServerVariables["REMOTE_ADDR"];

	if (Request.HttpMethod.Equals("GET"))
	{
		//Get
	}
	if (Request.HttpMethod.Equals("POST"))
	{
		//Post
	}
}

如果要取得Get 或是 post傳來的參數

//Use this for GET values:
Request.QueryString["key"];

//And this for POST values
Request.Form["key"];

/*Also, this will work if you don't care whether it comes from GET or POST, 
or the HttpContext.Items collection:
*/
Request["key"];

如果不確定Key,也可以用迴圈去取得所有的參數(POST)


//This code will list out all the form variables that are being sent in a POST. 
//This way you can see if you have the proper names of the post values
String[] keys = Request.Form.AllKeys;
for (int i= 0; i < keys.Length; i++) 
{
   Response.Write(keys[i] + ": " + Request.Form[keys[i]] + "<br>");
}

//Or Use foreach
foreach(String pKey in keys)
{
   String key = pKey ;
   String value = Request[key];
}
取得GET的參數

// 取得集合
NameValueCollection nvc = Request.QueryString; 
foreach (string key in nvc.Keys)
{
    Response.Write("{0} => {1}", key, nvc[key]);
}

Request.ServerVariables: 檢視伺服器環境變數的值 

Request.ServerVariables["REMOTE_ADDR"]   發出請求的遠程主機的 IP 位址