Avatar of tia_kamakshi
tia_kamakshiFlag 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
Avatar of tia_kamakshi
tia_kamakshi
Flag of United Arab Emirates image

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

Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

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

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
Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

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

User generated image
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.
Avatar of tia_kamakshi
tia_kamakshi
Flag of United Arab Emirates image

ASKER

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

Thanks
Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

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.
Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

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

Avatar of tia_kamakshi
tia_kamakshi
Flag of United Arab Emirates image

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
Avatar of Robert Schutt
Robert Schutt
Flag of Netherlands image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of tia_kamakshi
tia_kamakshi
Flag of United Arab Emirates image

ASKER

Great Answer!!..Many Thanks
C#
C#

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

98K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo