如何替换url-parameter

本文关键字:url-parameter 替换 何替换 | 更新日期: 2023-09-27 17:49:37

给定的URL是http://localhost:1973/Services.aspx?idProject=10&idService=14

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

正则表达式字符串。替换,子字符串或LinQ -我有点卡住了。

提前谢谢你

蒂姆


我以以下结尾,这对我来说是有效的,因为这个页面只有这两个参数:

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

但是谢谢你的建议

如何替换url-parameter

我要这样做:

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

这是我的实现:

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

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<KeyValuePair<string,object>>可能比当前分隔的字符串更好。

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

最直接的方法是String.Replace,但是如果您的uri看起来像http://localhost:1212/base.axd?id=12&otherId=12

,您将最终遇到问题。

我最近发布了UriBuilderExtended,这是一个库,可以通过扩展方法编辑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获取库。

更多的例子在这里。

欢迎留言和祝愿

最健壮的方法是使用Uri类解析字符串,更改参数值,然后构建结果。

url的工作方式有很多细微差别,虽然您可以尝试使用自己的正则表达式来实现这一点,但处理所有情况可能会很快变得复杂。

所有其他方法都有子字符串匹配等问题,我甚至没有看到Linq在这里是如何应用的。

我也有同样的问题,我用下面三行代码解决了这个问题,我从这里的注释中得到(像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#是很简单的。