Request简单使用:
说起Request,在项目中基本都必须有用到,这里记录一下我了解到的关于Request的内容:
直接代码:
非常基本的当然有Reqeust.Form和Request.QueryString,两者的区别这里不多说.
1 String name=Request.Form["Name"];//post请求或者表单上传 2 3 String id=Request.QueryString["ID"];//get请求 4 5 String value=Request["Value"];//拿到所有过来的参数
其实QueryString也可以当成一个数组
int Count = System.Web.HttpContext.Current.Request.QueryString.Count;//Count属性可以得到传递过来的参数个数 //通过Keys属性得到"键值对"中的键值 for (int i = 0; i < Count; i++) { if(System.Web.HttpContext.Current.Request.QueryString.Keys[i].ToLower().Equals("page")) { String value=System.Web.HttpContext.Current.Request.QueryString[i]; } }
清除QueryString:
1 /// <summary> 2 /// 清除Request.QueryString 3 /// </summary> 4 /// <param name="name"></param> 5 public void RemoveQueryString(string name) 6 { 7 enableQueryStringWriting(); 8 Request.QueryString.Remove(name); 9 } 10 11 private void enableQueryStringWriting() 12 { 13 var qs = Request.QueryString; 14 15 var queryString = (NameValueCollection)Request.GetType().GetField( 16 "_queryString", 17 BindingFlags.NonPublic | BindingFlags.Instance 18 ).GetValue(Request); 19 20 PropertyInfo readOnlyInfo = queryString.GetType().GetProperty( 21 "IsReadOnly", 22 BindingFlags.NonPublic | BindingFlags.Instance 23 ); 24 25 readOnlyInfo.SetValue(queryString, false, null); 26 }
最后提一下,上述是通过C#代码来操作Request对象,正常情况下,使用JS来操作也是比较多的,代码如下:
1 //获取QueryString的数组 2 3 function getQueryString(){ 4 5 var result = location.search.match(new RegExp("[?&][^?&]+=[^?&]+","g")); 6 7 if(result == null){ 8 9 return ""; 10 11 } 12 13 for(var i = 0; i < result.length; i++){ 14 15 result[i] = result[i].substring(1); 16 17 } 18 19 return result; 20 21 } 22 //根据QueryString参数名称获取值 23 24 function getQueryStringByName(name){ 25 26 var result = location.search.match(new RegExp("[?&]" + name+ "=([^&]+)","i")); 27 28 if(result == null || result.length < 1){ 29 30 return ""; 31 32 } 33 34 return result[1]; 35 36 } 37 //根据QueryString参数索引获取值 38 39 function getQueryStringByIndex(index){ 40 41 if(index == null){ 42 43 return ""; 44 45 } 46 47 var queryStringList = getQueryString(); 48 49 if (index >= queryStringList.length){ 50 51 return ""; 52 53 } 54 55 var result = queryStringList[index]; 56 57 var startIndex = result.indexOf("=") + 1; 58 59 result = result.substring(startIndex); 60 61 return result; 62 63 } 64 65
END!