C# 如何替换url参数?
给定的URL类似于C# 如何替换url参数?,c#,.net,asp.net,url,string,C#,.net,Asp.net,Url,String,给定的URL类似于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("Serv
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));
但是感谢您的建议:)最可靠的方法是使用Uri类来解析字符串,更改te param值,然后构建结果 URL的工作方式有很多细微差别,虽然您可以尝试使用自己的正则表达式来实现这一点,但处理所有情况可能会很快变得复杂
所有其他方法都会遇到子字符串匹配等问题,我甚至不知道Linq在这里是如何应用的 最简单的方法是
String.Replace
,但是如果uri看起来像http://localhost:1212/base.axd?id=12&otherId=12
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";
我在一个旧的代码示例中发现了这一点,不需要太多的改进,使用
IEnumerable
可能比使用当前的delimetered字符串更好
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;
}
用法
这就是我要做的:
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");
或:
我也有同样的问题,我用下面三行代码解决了这个问题,这三行代码是我从这里得到的(就像Stephen Oberauer的解决方案,但没有太多的设计):
这是使用VB.NET的解决方案,但到C的转换是直接向前的。以下是我的实现:
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
我最近发布了一个库,它通过扩展方法轻松编辑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()
中获取的,因为它有时呈现的效果与您期望的不同
你可以通过图书馆
更多的例子
评论和愿望是最受欢迎的。简单的字符串替换无法正确满足OP的要求。我知道,因此我声明(尽管是含蓄的)最直接的方法(如要求的)不是正确的方法。实际上,我以使用string.Replace(见我的编辑)结束,这符合我的要求。@Tim-如果这是你当时最喜欢的答案,我能至少得到一张赞成票吗?谢谢。我使用了一个简单的替换,因为页面上只有这两个参数,但您的答案是一个更好的示例;)您应该声明keyvalue应该是正确的uri编码,这样才能工作。如果我想发送
query=?est
,它将创建一个无效的查询字符串为什么要将RawUrl传递给ParseQueryString?查询字符串和URL之间存在差异。你不应该先拆分URL来提取查询字符串吗?是的,答案很好,但是如果你传递了整个URL,那么你的第一个参数的键将看起来像http://localhost:50819/Request?pagenumber
而不仅仅是页码
。谢谢,这看起来很有希望,我以后会仔细看看。漂亮而且没有副作用
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 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();