Avatar of tia_kamakshi
tia_kamakshi
Flag for United Arab Emirates asked on

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

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.
C#

Avatar of undefined
Last Comment
tia_kamakshi

8/22/2022 - Mon
tia_kamakshi

ASKER
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 Schutt

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

ASKER
@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
Your help has saved me hundreds of hours of internet surfing.
fblack61
Robert Schutt

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.
tia_kamakshi

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

Thanks
Robert Schutt

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.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Robert Schutt

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

tia_kamakshi

ASKER
@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
ASKER CERTIFIED SOLUTION
Robert Schutt

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
tia_kamakshi

ASKER
Great Answer!!..Many Thanks
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy