How to remove partucular list of querystring from current page url querystring in c#2.0

tia_kamakshi
tia_kamakshi used Ask the Experts™
on
hi Experts,
Say my current page url has got http://localhost:2345/english/faq.aspx?faqid=12123&cid=4545&intcid=65456&h=man
string excludeQuerystring = DynConfig.Item("GoogleSEOLinkSettings/ExcludeQuerystring"); //this is the list of my exclude querystring (cid,intcid,del)

querystring = HttpContext.Current.Request.Url.AbsoluteUri.Split('?')[1]; //I will get faqid=12123&cid=4545,intcid=65456

StringBuilder fullQueryString = new StringBuilder();

if (!string.IsNullOrEmpty(excludeQuerystring) && !string.IsNullOrEmpty(querystring))
{
	string[] strEQ = excludeQuerystring.Split(',');  //making a array of excluded querystrings

	NameValueCollection navValues = HttpUtility.ParseQueryString(querystring);  //getting the list of querystring in NameValueCollection

	if (navValues.Count > 0)
	{
		string[] strQ = navValues.AllKeys;
		if(strQ.Length>0)
		{
			
		}
	}
}	

querystring= ?+faqid=12123&h=man //here I want updated querystring which does not have any querystring which is there in my excludeQuerystring

Open in new window


I am confused how to get this, actually I want to make a function which will do this all.

Please suggest!!

EDIT:

I changed the code for above implementation. Please see the code.

 protected void Page_Load(object sender, EventArgs e)
        {
            string querystring = string.Empty;

            string excludeList = "cid,intcid,del";

            if (!string.IsNullOrEmpty(excludeList))
            {
                string getFinalString = GetQueryString(excludeList);
                getFinalString = "?" + getFinalString;
            }
        }

        public string GetQueryString(string excludeArray)
        {
            string retQueryString = string.Empty;
            if (excludeArray.IndexOf(",") != -1)
            {
                string[] strArray = excludeArray.Split(",".ToCharArray());
                NameValueCollection filtered = new NameValueCollection();

                filtered.Add(HttpUtility.ParseQueryString(Request.Url.Query));
                if (filtered.HasKeys())
                {
                    foreach (string strMatch in strArray)
                    {
                        filtered.Remove(strMatch);
                    }
                    retQueryString = filtered.ToString();
                }
            }

            return retQueryString;
        }

Open in new window


Now when I am going to convert back to querystring from NameValueCollection existing keys
retQueryString = filtered.ToString();

Open in new window

what code will be written for this as I am not able to convert it back to string.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Author

Commented:
Hi Experts,

Any suggestions for below code for above issue, what changes can I do so that there would not be any Exceptions.
 protected void Page_Load(object sender, EventArgs e)
        {
            string querystring = string.Empty;

            string excludeList = "cid,intcid,del";

            if (!string.IsNullOrEmpty(excludeList))
            {
                string getFinalString = GetQueryString(excludeList);
                getFinalString = "?" + getFinalString;
            }
        }

        public string GetQueryString(string excludeArray)
        {
            string retQueryString = string.Empty;
            if (excludeArray.IndexOf(",") != -1)
            {
                string[] strArray = excludeArray.Split(",".ToCharArray());
                NameValueCollection filtered = new NameValueCollection();

                filtered.Add(HttpUtility.ParseQueryString(Request.Url.Query));
                if (filtered.HasKeys())
                {
                    foreach (string strMatch in strArray)
                    {
                        filtered.Remove(strMatch);
                    }
                    retQueryString = ConstructQueryString(filtered);
                }
            }

            return retQueryString;
        }

        public static string ConstructQueryString(NameValueCollection parameters)
        {
            List<string> items = new List<string>();

            foreach (String name in parameters)
                items.Add(String.Concat(name, "=", System.Web.HttpUtility.UrlEncode(parameters[name])));

            return String.Join("&", items.ToArray());
        }

Open in new window

Robert SchuttSoftware Engineer

Commented:
What Exception are you getting? Sometimes it's not possible or worth the effort to avoid an Exception, but handle it with try/catch.

Author

Commented:
@robert_schutt, I am not getting any Exception till now, can you please suggest any code changes on above solution for better performances. ( I am using C#2.0) or is there any way to handle my above problem.

Thanks
OWASP Proactive Controls

Learn the most important control and control categories that every architect and developer should include in their projects.

Robert SchuttSoftware Engineer

Commented:
The solution you have now works with the current data (see picture).

debug result
The way you do it now has a couple of potential problems: if you don't specify an excludeList then the result is empty. Also, if there's no querystring to begin with or everything is deleted then the result is "?" which sometimes is not wanted but I can't be sure in your case if that is by design.

If you want to avoid splitting and re-joining the individual parts you could probably do all this with one regEx.Replace instead.

Author

Commented:
@can you please suggest your code sample for above approach.

Thanks
Robert SchuttSoftware Engineer

Commented:
With a regular expression you mean? I was already working on that, this seems to do the trick:

string getFinalString = "?" + Regex.Replace("&" + Request.Url.Query.Substring(1), "&(" + excludeList.Replace(",", "|") + ")=[^&]*", "", RegexOptions.IgnoreCase).Substring(1);

Open in new window


It may need some more checking but I checked that it works when the first and/or last item is removed, which seem the main stumbling blocks.

So what I did is remove the first character and make sure that every part has the same construction: a "&" followed by the name of one of the querystring parts we want to remove, followed by an equals sign, followed by its value which consists of 0 or more of any character but "&". If that matches, it is removed. Then at the end, the first character is replace by a question mark again. Actually that part throws an exception if there's nothing left due to the .Substring(1) which you can't do on an empty string. So there's some checking to be added.
Robert SchuttSoftware Engineer

Commented:
How about this one, regex overkill...? ;-)

string getFinalString = Regex.Replace(Regex.Replace(Regex.Replace(Request.Url.Query, @"^\?", "&"), "&(" + excludeList.Replace(",", "|") + ")=[^&]*", "", RegexOptions.IgnoreCase), "^&", "?");

Open in new window

Author

Commented:
@robert_schutt, when trying your above solution I am getting "startIndex cannot be larger than length of string.
Parameter name: startIndex"

Please suggest what extra check do I need to put
Software Engineer
Commented:
yep, that's the problem with an empty string. The second one should solve that. Here is a version with comments:

            string getFinalString = Regex.Replace(
                Regex.Replace(
                    Regex.Replace(
                        Request.Url.Query,                             // Start with the Querystring and replace
                        @"^\?",                                        // the question mark at the beginning
                        "&"),                                          // with an ampersand,
                    "&(" + excludeList.Replace(",", "|") + ")=[^&]*",  // so all parts will look the same and can be
                    "",                                                // removed when they contain a part in the exclude list
                    RegexOptions.IgnoreCase),                          // no matter if they are in capitals or not.
                "^&",                                                  // Then, replace the first &, if there is one,
                "?");                                                  // back to a question mark

Open in new window

Author

Commented:
Great Answer!!..Many Thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial