如何替换url-parameter?

给出的是一个像http://localhost:1973/Services.aspx?idProject=10&idService=14

替换两个url参数值的最直接的方法是什么(例如10到12和14到7)?

Regex,String.Replace,Substring或LinQ – 我有点卡住了。

先感谢您,

蒂姆


我结束了跟随,这对我有用,因为这个页面只有这两个参数:

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

但是谢谢你的建议:)

我在一个旧的代码示例中发现了这一点,并不需要太多改进它,采用IEnumerable>可能比当前的delimeted字符串更好。

  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; } 

用法

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

这就是我要做的:

 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; } } 

用法:

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

要么:

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

C#HttpUtility.ParseQueryString实用程序将为您做繁重的工作。 您将希望在最终版本中执行更强大的空值检查。

  // 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"; 

这是我的实施:

 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; } } 

以下是一些例子:

 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 

最简单的方法是String.Replace ,但如果你的uri看起来像http://localhost:1212/base.axd?id=12&otherId=12 ,你最终会遇到问题

最强大的方法是使用Uri类来解析字符串,更改te param值,然后构建结果。

URL的工作方式有很多细微差别,虽然您可以尝试使用自己的正则表达式来执行此操作,但很快就会处理所有情况。

所有其他方法都会遇到子串匹配等问题,我甚至不知道Linq如何应用于此。

我最近发布了UriBuilderExtended ,这是一个通过扩展方法轻松编辑UriBuilder对象上的查询字符串的库。

您基本上只需在UriBuilder函数中使用当前URL字符串创建UriBuilder对象,通过扩展方法修改查询,并从UriBuilder对象构建新的URL字符串。

快速举例:

 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(); 

URL字符串是从builder.Uri.ToString() ,而不是builder.ToString()因为它有时会呈现与您期望的不同。

您可以通过NuGet获取库。

这里有更多例子。

欢迎提出意见和祝愿。

我有同样的问题,我用以下三行代码解决了这个问题,我从这里得到了一些代码(比如Stephen Oberauer的解决方案,但不太过分了):

  ' 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()) 

这是使用VB .NET的解决方案,但转换为C#非常简单。