How to replace url parameter?

a URL is http://localhost:1973/Services.aspx?idProject=10&idService=14 , for example http://localhost:1973/Services.aspx?idProject=10&idService=14 .

What is the easiest way to replace both url parameter values ​​(for example, from 10 to 12 and from 14 to 7)?

Regex, String.Replace, Substring or LinQ - I'm a little stuck.

Thanks in advance,

Tim


I ended up with the following, which works for me, because this page has only these two options:

 string newUrl = url.Replace(url.Substring(url.IndexOf("Services.aspx?") + "Services.aspx?".Length), string.Format("idProject={0}&idService={1}", Services.IdProject, Services.IdService)); 

But thanks for your suggestions :)

+6
source share
8 answers

I found this in an old code example, it would not take much to improve it, taking IEnumerable<KeyValuePair<string,object>> may be better than the current separation line.

  public static string AppendQuerystring( string keyvalue) { return AppendQuerystring(System.Web.HttpContext.Current.Request.RawUrl, keyvalue); } public static string AppendQuerystring(string url, string keyvalue) { string dummyHost = "http://www.test.com:80/"; if (!url.ToLower().StartsWith("http")) { url = String.Concat(dummyHost, url); } UriBuilder builder = new UriBuilder(url); string query = builder.Query; var qs = HttpUtility.ParseQueryString(query); string[] pts = keyvalue.Split('&'); foreach (string p in pts) { string[] pts2 = p.Split('='); qs.Set(pts2[0], pts2[1]); } StringBuilder sb = new StringBuilder(); foreach (string key in qs.Keys) { sb.Append(String.Format("{0}={1}&", key, qs[key])); } builder.Query = sb.ToString().TrimEnd('&'); string ret = builder.ToString().Replace(dummyHost,String.Empty); return ret; } 

Using

  var url = AppendQueryString("http://localhost:1973/Services.aspx?idProject=10&idService=14","idProject=12&idService=17"); 
+2
source

This is what I would do:

 public static class UrlExtensions { public static string SetUrlParameter(this string url, string paramName, string value) { return new Uri(url).SetParameter(paramName, value).ToString(); } public static Uri SetParameter(this Uri url, string paramName, string value) { var queryParts = HttpUtility.ParseQueryString(url.Query); queryParts[paramName] = value; return new Uri(url.AbsoluteUriExcludingQuery() + '?' + queryParts.ToString()); } public static string AbsoluteUriExcludingQuery(this Uri url) { return url.AbsoluteUri.Split('?').FirstOrDefault() ?? String.Empty; } } 

Using:

 string oldUrl = "http://localhost:1973/Services.aspx?idProject=10&idService=14"; string newUrl = oldUrl.SetUrlParameter("idProject", "12").SetUrlParameter("idService", "7"); 

Or:

 Uri oldUrl = new Uri("http://localhost:1973/Services.aspx?idProject=10&idService=14"); Uri newUrl = oldUrl.SetParameter("idProject", "12").SetParameter("idService", "7"); 
+13
source

C # utility HttpUtility.ParseQueryString will do the hard work for you. You will want to make even more reliable zero checking in your final version.

  // Let the object fill itself // with the parameters of the current page. var qs = System.Web.HttpUtility.ParseQueryString(Request.RawUrl); // Read a parameter from the QueryString object. string value1 = qs["name1"]; // Write a value into the QueryString object. qs["name1"] = "This is a value"; 
+8
source

Here is my implementation:

 using System; using System.Collections.Specialized; using System.Web; // For this you need to reference System.Web assembly from the GAC public static class UriExtensions { public static Uri SetQueryVal(this Uri uri, string name, object value) { NameValueCollection nvc = HttpUtility.ParseQueryString(uri.Query); nvc[name] = (value ?? "").ToString(); return new UriBuilder(uri) {Query = nvc.ToString()}.Uri; } } 

and here are some examples:

 new Uri("http://host.com/path").SetQueryVal("par", "val") // http://host.com/path?par=val new Uri("http://host.com/path?other=val").SetQueryVal("par", "val") // http://host.com/path?other=val&par=val new Uri("http://host.com/path?PAR=old").SetQueryVal("par", "new") // http://host.com/path?PAR=new new Uri("http://host.com/path").SetQueryVal("par", "/") // http://host.com/path?par=%2f new Uri("http://host.com/path") .SetQueryVal("p1", "v1") .SetQueryVal("p2", "v2") // http://host.com/path?p1=v1&p2=v2 
+4
source

The easiest way is String.Replace , but you will have problems if your uri looks like http://localhost:1212/base.axd?id=12&otherId=12

+2
source

The most reliable way would be to use the Uri class to parse a string, change the values ​​of the te parameter, and then construct the result.

There are many nuances about how URLs work, and although you can try to collapse your own regular expression so that it can quickly complicate the handling of all cases.

All other methods will have problems with substring matching, etc., and I don’t even see how Linq is applied here.

+1
source

I recently published UriBuilderExtended , which is a library that allows you to edit query strings on UriBuilder objects like the wind through extension methods.

Basically, you create a UriBuilder object with the current URL string in the constructor, modify the request using extension methods, and create a new URL string from the UriBuilder object.

Quick example:

 string myUrl = "http://www.example.com/?idProject=10&idService=14"; UriBuilder builder = new UriBuilder(myUrl); builder.SetQuery("idProject", "12"); builder.SetQuery("idService", "7"); string newUrl = builder.Url.ToString(); 

The URL string is obtained from builder.Uri.ToString() , not builder.ToString() , as it sometimes differs from what you expect.

You can get the library through NuGet .

Additional examples here .

Comments and suggestions are welcome.

+1
source

I have the same problem, and I solved it with the following three lines of code that I get from the comments here (e.g. Stephen Oberauer's solution, but less overworked):

  ' EXAMPLE: ' INPUT: /MyUrl.aspx?IdCat=5&Page=3 ' OUTPUT: /MyUrl.aspx?IdCat=5&Page=4 ' Get the URL and breaks each param into Key/value collection: Dim Col As NameValueCollection = System.Web.HttpUtility.ParseQueryString(Request.RawUrl) ' Changes the param you want in the url, with the value you want Col.Item("Page") = "4" ' Generates the output string with the result (it also includes the name of the page, not only the params ) Dim ChangedURL As String = HttpUtility.UrlDecode(Col.ToString()) 

This is a solution using VB.NET, but converting to C # is not easy.

0
source

Source: https://habr.com/ru/post/885431/


All Articles