Get all values of a NameValueCollection to a string - c#

I have the following code:
string Keys = string.Join(",",FormValues.AllKeys);
I was trying to play around with the get:
string Values = string.Join(",", FormValues.AllKeys.GetValue());
But of course that doesn't work.
I need something similar to get all the values, but I don't seem to find the appropriate code to do the same.
P.S: I do not want to use a foreach loop since that beats the purpose of the first line of code.

var col = new NameValueCollection() { { "a", "b" }, { "1", "2" } }; // collection initializer
var values = col.Cast<string>().Select(e => col[e]); // b, 2
var str = String.Join(",", values ); // "b,2"
Also you can create an extension method:
public static string Join(this NameValueCollection collection, Func<string,string> selector, string separator)
{
return String.Join(separator, collection.Cast<string>().Select(e => selector(e)));
}
Usage:
var s = c.Join(e => String.Format("\"{0}\"", c[e]), ",");
Also you can easily convert NameValueCollection to more handy Dictionary<string,string> so:
public static IDictionary<string,string> ToDictionary(this NameValueCollection col)
{
return col.AllKeys.ToDictionary(x => x, x => col[x]);
}
Gives:
var d = c.ToDictionary();
As I found using Reflector, NameValueCollection.AllKeys internally performs a loop to gather all te keys, so it seems that c.Cast<string>() is more preferable.

string values = string.Join(",", collection.AllKeys.Select(key => collection[key]));

Following creates a string from URL parameter list.
string.Join(", ",
Request.QueryString
.AllKeys
.Select(key => key + ": " + Request.QueryString[key])
.ToArray())
i.e
page.aspx?id=75&page=3&size=7&user=mamaci
would be
id: 75, page: 3, size: 7, user: mamaci

string values =
string.Join(",", FormValues.AllKeys.SelectMany(key => FormValues.GetValues(key)));
Edit: The other answers may or may not be what you want. They appear simpler, but the results might not be what you are looking for in all circumstances, but then again, they might be (your mileage may vary).
Note that a NameValueCollection is not a 1:1 mapping like a dictionary. You can add multiple values for the same key, which is why a function like .GetValues(key) returns an array, not a single string.
If you have a collection where you have added
collection.Add("Alpha", "1");
collection.Add("Alpha", "2");
collection.Add("Beta", "3");
Retrieving collection["Alpha"] yields "1,2". Retrieving collection.GetValues("Alpha") yields { "1", "2" }. Now, it just so happens that you are using a comma to join your values together into a single string, so this disparity is hidden. However, if you were joining on another value, such as an exclamation point, the results of the other answers would be
"1,2!3"
And the code here would be
"1!2!3"
Use the snippet that demonstrates the behavior you prefer.

In cases where you have parsed the query string with System.Web.HttpUtility.ParseQueryString(...) you can just use ToString() and you don't have to re-invent the wheel.
Even though result is NameValueCollection, the underlying type is HttpValueCollection which has the necessary ToString() override to build back a query string.

I'm using Azure DocumentDB as my logging mechanism, hence writing a dynamic object, but you get the gist...
public class LogErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
int responseCode = new int();
// Has the exception been handled. Also, are custom errors enabled
if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
return;
// Check if custom exception, if so get response code
if (filterContext.Exception is CustomException)
responseCode = (int)((CustomException)filterContext.Exception).Code;
// Log exception
string id = Logging.Write(LogType.Error, new
{
ResponseCode = responseCode,
Exception = new
{
Message = filterContext.Exception.Message,
Data = filterContext.Exception.Data,
Source = filterContext.Exception.Source,
StackTrace = filterContext.Exception.StackTrace,
InnerException = filterContext.Exception.InnerException != null ? new
{
Message = filterContext.Exception.InnerException.Message,
Data = filterContext.Exception.InnerException.Data,
Source = filterContext.Exception.InnerException.Source,
StackTrace = filterContext.Exception.InnerException.StackTrace
} : null
},
Context = filterContext.Controller != null ? new
{
RouteData = filterContext.Controller.ControllerContext.RouteData,
QueryString = filterContext.Controller.ControllerContext.HttpContext.Request.Url.Query,
FormParams = filterContext.Controller.ControllerContext.HttpContext.Request.Form != null ? string.Join(";#", filterContext.Controller.ControllerContext.HttpContext.Request.Form.AllKeys.Select(key => key + ":" + filterContext.Controller.ControllerContext.HttpContext.Request.Form[key])) : string.Empty,
Model = (filterContext.Controller is Controller) ? ((Controller)filterContext.Controller).ModelState : null,
ViewBag = filterContext.Controller.ViewBag,
ViewData = filterContext.Controller.ViewData
} : null,
ActionResult = filterContext.Result != null ? filterContext.Result : null,
Referrer = filterContext.HttpContext.Request.UrlReferrer != null ? filterContext.HttpContext.Request.UrlReferrer : null
}).Result;
// Mark exception as handled and return
filterContext.ExceptionHandled = true;
// Test for Ajax call
if (IsAjax(filterContext))
{
// Construct appropriate Json response
filterContext.Result = new JsonResult()
{
Data = new
{
code = responseCode,
id = id,
message = filterContext.Exception.Message
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
var result = new ViewResult();
result.ViewName = "_CustomError";
result.ViewBag.CorrelationId = id;
filterContext.Result = result;
}
}
/// <summary>
/// Determine if the request is from an Ajax call
/// </summary>
/// <param name="filterContext">The request context</param>
/// <returns>True or false for an Ajax call</returns>
private bool IsAjax(ExceptionContext filterContext)
{
return filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
}
}
I have a CustomException where I check for a application-set response code.
Additionally, I take the querystring, form data, and the model so that I can see the values passed before and after the model binder.
If its and Ajax call, I return a Json-formatted response. Otherwise, I return a custom error page.

List<string> values = new List<string>();
values.AddRange(all.AllKeys.SelectMany(all.GetValues).Where(getValues => getValues != null));
string Values = string.Join(",", values.ToArray());
You can try something like the above.

Related

JObject Parse Data with a variable as the value

I am trying to decipher the correct syntax for using JObject Parse when I need to have one of the values set by a variable. This is for using Algolia to push a new object to my search index.
songIndexHelper.PartialUpdateObject(JObject.Parse(#"{""ApprovalFL"":"true",
""objectID"":"'+Accepted.Value+'"}"));
I receive Accepted.Value from my function argument. For example, Accepted.Value could equal something like 98. Also, true should be formatted as boolean instead of a string. The above is my attempt. How should I fix my syntax?
I'm following this documentation from Algolia: https://www.algolia.com/doc/api-reference/api-methods/partial-update-objects/
For more context, here is the above line in the function:
public ActionResult Index(int? Accepted, int? Denied)
{
var accountInfo = EntityDataAccess.GetAccountInfoByUserID(User.Identity.GetUserId());
if(accountInfo == null || accountInfo.AdminFL == false || accountInfo.LabelFL == true)
{
return RedirectToAction("Index", "Home");
}
else
{
if(Accepted != null)
{
EntityDataAccess.AcceptSong(Accepted.Value);
var songIndexHelper = HttpContext.Application.Get("SongIndexHelper") as IndexHelper<SongAlgoliaModel>;
songIndexHelper.PartialUpdateObject(JObject.Parse(#"{""ApprovalFL"":""true"",
""objectID"":""Accepted.Value""}"));
}
This should produce what you are looking for:
String json = "{\"ApprovalFL\":true,\"objectID\":" + Accepted.Value.ToString() + "}";
which is:
{"ApprovalFL":true,"objectID":98}
songIndexHelper.PartialUpdateObject(JObject.Parse(#"{""ApprovalFL"":""true"",
""objectID"":""Accepted.Value""}"));
should be:
songIndexHelper.PartialUpdateObject(JObject.Parse(#"{""ApprovalFL"":true,
""objectID"":" +Accepted.Value+ "}"));
The key is to use + to concatenate in the value of Accepted, and not wrap true in quotes.
Another approach I would suggest is not using strings at all. Consider an approach like:
var bob = new { ApprovalFL = true, objectID = Accepted.Value};
var obj = JObject.FromObject(bob);
songIndexHelper.PartialUpdateObject(obj);

How to check if value is multiple or not in key value c#

Here is the method:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
var parameters = filterContext.ActionParameters.ToArray();
if (parameters.Count() > 0)
{
foreach (KeyValuePair<string, object> data in parameters)
{
singleparameters = singleparameters + data.Key + ":" + " " + data.Value + ",";
}
singleparameters = singleparameters.Remove(singleparameters.LastIndexOf(','));
I want to check if data value contain single or multiple value.
If the data is single data then key:req and value: pagerecords:200.
If the data contains multiple values there then check if values contain array or single value. Fot example: key:req and values: pagerecords:200, pageinfo:"adsa", count:0, filter: records:200,cotnain:"asa"
I want to check condition an access that..
I am newbie in this area so please give me any suggestion
for more clarification
foreach (KeyValuePair<string, object> data in parameters)
{
if (data.Key == "request" && data.value is jqGridRequest)
{
var fields = g.GetType().GetProperties();
bool hasSingleValue = fields.Count(x => x.GetValue(g, null) != null) == 1;
}
}
as From screenshot its clear that the data.value type is jqGridRequest, so we can directly make use of the object to check or get the desired value, Actually you dont need to do looping also , Directly cast the object and make use of property using if else.
jqGridRequest request = data.value as jqGridRequest;
if (request != null)
{
int pageindex = request.PageIndex;
//// so on other properties, get it and use it directly without looping.
}
This can help you check the value is single or multiple:
var valueFields = data.Value.GetType().GetFields();
var fieldNumber = valueFields.Length;
//If fieldNumber = 1 it is single, otherwise it is multiple
Then you can check if it contains any array
foreach(var fld in valueFields) {
bool isArray = fld.FieldType.IsArray; //true if the field is an array
}

How can I convert a JSON string to URL parameters (GET request)?

I have the following JSON which has to be converted to URL parameters for a GET request.
An example is given here, however due to the complexity of this object, there can be multiple line_items_attributes each with the given values as shown, I'm having difficulties passing on the correct one.
I've also tried to just serialize the JSON object and pass on that value but that did not solve the issue either.
{
"purchase_invoice":
{
"date":"14/04/2015",
"due_date":"14/04/2015",
"contact_id":500,
"contact_name":"TestContact",
"reference":"TestReference",
"line_items_attributes":[
{
"unit_price":10.00,
"quantity":1,
"description":"TestLineItemAttDesc",
"tax_code_id":1,
"ledger_account_id":501,
"tax_rate_percentage":19.0,
"tax_amount":1.60
}]
}
}
I've been searching for a while now but without much luck. Any insights are appreciated and most welcome!
This is calling an API which does not support the incoming data in JSON format, so doing this server-side or changing the web service to support data in JSON format is not possible.
x-www-form-urlencoded content is, essentially, a flat sequence of key/value tuples, and as explained in this answer to How do I use FormUrlEncodedContent for complex data types? by Tomalak, there is no canonical way to transform a hierarchical, nested key/value structure into a flat one.
Nevertheless, from the accepted answer to this question, this example from the Stripe API, and the question mentioned above, it seems that it is common to flatten parameters inside complex nested objects by surrounding their keys in brackets and appending them to the topmost key like so:
{
{ "purchase_invoice[date]", "14/04/2015" }
{ "purchase_invoice[due_date]", "14/04/2015" }
{ "purchase_invoice[contact_id]", "500" }
{ "purchase_invoice[contact_name]", "TestContact" }
{ "purchase_invoice[reference]", "TestReference" }
{ "purchase_invoice[line_items_attributes][0][unit_price]", "10" }
{ "purchase_invoice[line_items_attributes][0][quantity]", "1" }
{ "purchase_invoice[line_items_attributes][0][description]", "TestLineItemAttDesc" }
{ "purchase_invoice[line_items_attributes][0][tax_code_id]", "1" }
{ "purchase_invoice[line_items_attributes][0][ledger_account_id]", "501" }
{ "purchase_invoice[line_items_attributes][0][tax_rate_percentage]", "19" }
{ "purchase_invoice[line_items_attributes][0][tax_amount]", "1.6" }
}
If this is what you want, you can generate such key/value pairs with json.net using the following extension methods:
public static partial class JsonExtensions
{
public static string ToUrlEncodedQueryString(this JContainer container)
{
return container.ToQueryStringKeyValuePairs().ToUrlEncodedQueryString();
}
public static IEnumerable<KeyValuePair<string, string>> ToQueryStringKeyValuePairs(this JContainer container)
{
return container.Descendants()
.OfType<JValue>()
.Select(v => new KeyValuePair<string, string>(v.ToQueryStringParameterName(), (string)v));
}
public static string ToUrlEncodedQueryString(this IEnumerable<KeyValuePair<string, string>> pairs)
{
return string.Join("&", pairs.Select(p => HttpUtility.UrlEncode(p.Key) + "=" + HttpUtility.UrlEncode(p.Value)));
//The following works but it seems heavy to construct and await a task just to built a string:
//return new System.Net.Http.FormUrlEncodedContent(pairs).ReadAsStringAsync().Result;
//The following works and eliminates allocation of one intermediate string per pair, but requires more code:
//return pairs.Aggregate(new StringBuilder(), (sb, p) => (sb.Length > 0 ? sb.Append("&") : sb).Append(HttpUtility.UrlEncode(p.Key)).Append("=").Append(HttpUtility.UrlEncode(p.Value))).ToString();
//Answers from https://stackoverflow.com/questions/3865975/namevaluecollection-to-url-query that use HttpUtility.ParseQueryString() are wrong because that class doesn't correctly escape the keys names.
}
public static string ToQueryStringParameterName(this JToken token)
{
// Loosely modeled on JToken.Path
// https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Linq/JToken.cs#L184
// By https://github.com/JamesNK
if (token == null || token.Parent == null)
return string.Empty;
var positions = new List<string>();
for (JToken previous = null, current = token; current != null; previous = current, current = current.Parent)
{
switch (current)
{
case JProperty property:
positions.Add(property.Name);
break;
case JArray array:
case JConstructor constructor:
if (previous != null)
positions.Add(((IList<JToken>)current).IndexOf(previous).ToString(CultureInfo.InvariantCulture)); // Don't localize the indices!
break;
}
}
var sb = new StringBuilder();
for (var i = positions.Count - 1; i >= 0; i--)
{
var name = positions[i];
// TODO: decide what should happen if the name contains the characters `[` or `]`.
if (sb.Length == 0)
sb.Append(name);
else
sb.Append('[').Append(name).Append(']');
}
return sb.ToString();
}
}
Then if you have a JSON string, you can parse it into a LINQ-to-JSON JObject and generate the query string like so:
var obj = JObject.Parse(jsonString);
var queryString = obj.ToUrlEncodedQueryString();
Alternatively, if you have some hierarchical data model POCO, you can generate your JObject from the model using JObject.FromObject():
var obj = JObject.FromObject(myModel);
var queryString = obj.ToUrlEncodedQueryString();
Demo fiddle here.
So the final URL would be easy to compute using any URL Encoding mechanism. In C#, we could do the following:
string json = "...";
string baseUrl = "http://bla.com/somepage?myJson="
string urlWithJson = baseUrl + System.Net.WebUtility.UrlEncode(json)
Is there any way you can POST the data or otherwise send a request body instead? It would seem slightly easier/cleaner.
Sounds like you need something which is x-www-form-urlencoded.
From your example, it would look like this:
purchase_invoice%5Bdate%5D=14%2F04%2F2015&purchase_invoice%5Bdue_date%5D=14%2F04%2F2015&purchase_invoice%5Bcontact_id%5D=500&purchase_invoice%5Bcontact_name%5D=TestContact&purchase_invoice%5Breference%5D=TestReference&purchase_invoice%5Bline_items_attributes%5D%5B0%5D%5Bunit_price%5D=10&purchase_invoice%5Bline_items_attributes%5D%5B0%5D%5Bquantity%5D=1&purchase_invoice%5Bline_items_attributes%5D%5B0%5D%5Bdescription%5D=TestLineItemAttDesc&purchase_invoice%5Bline_items_attributes%5D%5B0%5D%5Btax_code_id%5D=1&purchase_invoice%5Bline_items_attributes%5D%5B0%5D%5Bledger_account_id%5D=501&purchase_invoice%5Bline_items_attributes%5D%5B0%5D%5Btax_rate_percentage%5D=19&purchase_invoice%5Bline_items_attributes%5D%5B0%5D%5Btax_amount%5D=1.6
The best reference for this encoding that I'm aware of is the undocumented jQuery.param method on the jQuery JavaScript library.

Sorting a class string field property with numerical value [duplicate]

This question already has answers here:
Sorting of list contained strings having alphabetic/numeric
(2 answers)
Closed 8 years ago.
I have a class with one property "Name" containing names like "1_[AnnualRevenue]","2_[ResellerType]","3_xxx"....
my class is like
class xxx
{
private string fileName;
public string FileName
{
get { return fileName; }
set { fileName = value; }
}
}
And I am assigning the values to the object of the class. like xxx.FileName="1_[AnnualRevenue]";
Now I have a list class. And now sort the list according to this class property.
Now I want to sort the field according to the numeric order, I mean 1 first 2 second and so on.
And then write it to filestream.
Could any body help me with this.
Thanks in advance.
Since the property is a String but you want to sort it numerically, probably the best way would be to implement IComparable on your class and then put your custom sort code in the CompareTo method. Then you don't have to write a more complex Lambda statement each time you want to Sort a list, you can just call the Sort() method on the list.
You can also handle cases where the FileName property does not contain an underscore or is null, rather than getting exceptions in your OrderBy code (which is what would happen with most of the other answers).
I made a couple of other changes also - override the ToString method so you can easily display the value to the console window, and used Automatic property syntax for the FileName property so we can remove the backing field:
class xxx : IComparable<xxx>
{
public string FileName { get; set; }
public int CompareTo(xxx other)
{
// Short circuit if any object is null, if the
// Filenames equal each other, or they're empty
if (other == null) return 1;
if (FileName == null) return (other.FileName == null) ? 0 : -1;
if (other.FileName == null) return 1;
if (FileName.Equals(other.FileName)) return 0;
if (string.IsNullOrWhiteSpace(FileName))
return (string.IsNullOrWhiteSpace(other.FileName)) ? 0 : -1;
if (string.IsNullOrWhiteSpace(other.FileName)) return 1;
// Next, try to get the numeric portion of the string to compare
int thisIndex;
int otherIndex;
var thisSuccess = int.TryParse(FileName.Split('_')[0], out thisIndex);
var otherSuccess = int.TryParse(other.FileName.Split('_')[0], out otherIndex);
// If we couldn't get the numeric portion of the string, use int.MaxValue
if (!thisSuccess)
{
// If neither has a numeric portion, just use default string comparison
if (!otherSuccess) return FileName.CompareTo(other.FileName);
thisIndex = int.MaxValue;
}
if (!otherSuccess) otherIndex = int.MaxValue;
// Return the comparison of the numeric portion of the two filenames
return thisIndex.CompareTo(otherIndex);
}
public override string ToString()
{
return FileName;
}
}
Now, you can just call Sort on your list:
List<xxx> list = new List<xxx>
{
new xxx {FileName = "13_a"},
new xxx {FileName = "8_a"},
new xxx {FileName = null},
new xxx {FileName = "1_a"},
new xxx {FileName = "zinvalid"},
new xxx {FileName = "2_a"},
new xxx {FileName = ""},
new xxx {FileName = "invalid"}
};
list.Sort();
Console.WriteLine(string.Join("\n", list));
// Output (note the first two are the empty string and the null value):
//
//
// 1_a
// 2_a
// 8_a
// 13_a
// invalid
// zinvalid
You can use LINQ to do that for you
List<xxx> orderedList = unOrderedList.OrderBy(o => Convert.ToInt32(o.FileName.Split('_').First())).ToList();
Editted the answer on behalf of the comments - pointing out that indeed we need to convert to integers to order correctly.
You can do like following to sort the list:
List<xxx> list = new List<xxx>
{
new xxx { FileName = "3_a" },
new xxx { FileName = "1_a" },
new xxx { FileName = "2_a" },
new xxx { FileName = "8_a" }
};
var sorted = list.OrderBy(it => Convert.ToInt32(it.FileName.Split('_')[0]));//using System.Linq;
And you can write the list to disk file as below:
using (TextWriter tw = new StreamWriter("C:\\FileNames.txt"))
{
foreach (var item in sorted)
{
tw.WriteLine(item.FileName.ToString());
}
}

A clean way of generating QueryString parameters for web requests

I came across a problem in my current application that required fiddling with the query string in a base Page class (which all my pages inherit from) to solve the problem. Since some of my pages use the query string I was wondering if there is any class that provides clean and simple query string manipulation.
Example of code:
// What happens if I want to future manipulate the query string elsewhere
// (e.g. maybe rewrite when the request comes back in)
// Or maybe the URL already has a query string (and the ? is invalid)
Response.Redirect(Request.Path + "?ProductID=" + productId);
Use HttpUtility.ParseQueryString, as someone suggested (and then deleted).
This will work, because the return value from that method is actually an HttpValueCollection, which inherits NameValueCollection (and is internal, you can't reference it directly). You can then set the names/values in the collection normally (including add/remove), and call ToString -- which will produce the finished querystring, because HttpValueCollection overrides ToString to reproduce an actual query string.
I was hoping to find a solution built into the framework but didn't. (those methods that are in the framework require to much work to make it simple and clean)
After trying several alternatives I currently use the following extension method: (post a better solution or comment if you have one)
public static class UriExtensions
{
public static Uri AddQuery(this Uri uri, string name, string value)
{
string newUrl = uri.OriginalString;
if (newUrl.EndsWith("&") || newUrl.EndsWith("?"))
newUrl = string.Format("{0}{1}={2}", newUrl, name, value);
else if (newUrl.Contains("?"))
newUrl = string.Format("{0}&{1}={2}", newUrl, name, value);
else
newUrl = string.Format("{0}?{1}={2}", newUrl, name, value);
return new Uri(newUrl);
}
}
This extension method makes for very clean redirection and uri manipulation:
Response.Redirect(Request.Url.AddQuery("ProductID", productId).ToString());
// Will generate a URL of www.google.com/search?q=asp.net
var url = new Uri("www.google.com/search").AddQuery("q", "asp.net")
and will work for the following Url's:
"http://www.google.com/somepage"
"http://www.google.com/somepage?"
"http://www.google.com/somepage?OldQuery=Data"
"http://www.google.com/somepage?OldQuery=Data&"
Note that whatever route you use, you should really encode the values - Uri.EscapeDataString should do that for you:
string s = string.Format("http://somesite?foo={0}&bar={1}",
Uri.EscapeDataString("&hehe"),
Uri.EscapeDataString("#mwaha"));
What I usually do is just rebuild the querystring. Request has a QueryString collection.
You can iterator over that to get the current (unencoded) parameters out, and just join them together (encoding as you go) with the appropriate separators.
The advantage is that Asp.Net has done the original parsing for you, so you don't need to worry about edge cases such as trailing & and ?s.
I find my way for easy manipulating with get parameters.
public static string UrlFormatParams(this string url, string paramsPattern, params object[] paramsValues)
{
string[] s = url.Split(new string[] {"?"}, StringSplitOptions.RemoveEmptyEntries);
string newQueryString = String.Format(paramsPattern, paramsValues);
List<string> pairs = new List<string>();
NameValueCollection urlQueryCol = null;
NameValueCollection newQueryCol = HttpUtility.ParseQueryString(newQueryString);
if (1 == s.Length)
{
urlQueryCol = new NameValueCollection();
}
else
{
urlQueryCol = HttpUtility.ParseQueryString(s[1]);
}
for (int i = 0; i < newQueryCol.Count; i++)
{
string key = newQueryCol.AllKeys[i];
urlQueryCol[key] = newQueryCol[key];
}
for (int i = 0; i < urlQueryCol.Count; i++)
{
string key = urlQueryCol.AllKeys[i];
string pair = String.Format("{0}={1}", key, urlQueryCol[key]);
pairs.Add(pair);
}
newQueryString = String.Join("&", pairs.ToArray());
return String.Format("{0}?{1}", s[0], newQueryString);
}
Use it like
"~/SearchInHistory.aspx".UrlFormatParams("t={0}&s={1}", searchType, searchString)
Check This!!!
// First Get The Method Used by Request i.e Get/POST from current Context
string method = context.Request.HttpMethod;
// Declare a NameValueCollection Pair to store QueryString parameters from Web Request
NameValueCollection queryStringNameValCollection = new NameValueCollection();
if (method.ToLower().Equals("post")) // Web Request Method is Post
{
string contenttype = context.Request.ContentType;
if (contenttype.ToLower().Equals("application/x-www-form-urlencoded"))
{
int data = context.Request.ContentLength;
byte[] bytData = context.Request.BinaryRead(context.Request.ContentLength);
queryStringNameValCollection = context.Request.Params;
}
}
else // Web Request Method is Get
{
queryStringNameValCollection = context.Request.QueryString;
}
// Now Finally if you want all the KEYS from QueryString in ArrayList
ArrayList arrListKeys = new ArrayList();
for (int index = 0; index < queryStringNameValCollection.Count; index++)
{
string key = queryStringNameValCollection.GetKey(index);
if (!string.IsNullOrEmpty(key))
{
arrListKeys.Add(key.ToLower());
}
}

Categories