如何更换网址参数?参数、网址

2023-09-03 03:43:37 作者:我六毛你六毛咱俩一块二

给出就像 HTTP的URL://本地主机:1973 / Services.aspx idProject = 10安培; idService = 14

什么是最简单的方法来替代这两个URL参数值(例如10〜12和14〜7)?

What is the most straightforward way to replace both url-parameter values(for example 10 to 12 and 14 to 7)?

正则表达式,与string.replace,子串或LINQ - 我有点卡住。

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

感谢你在前进,

我结束了之后,这对我的工作,因为这个页面只有这两个参数:

I ended with following, that's working for me because this page has only these two parameter:

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

但还是非常感谢你的建议:)

But thank you for your suggestions :)

推荐答案

我在一个旧的code例如发现这一点,wouldnt花太多改进,采取了的IEnumerable< KeyValuePair<字符串,对象>> 可能会比目前的delimeted串好

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

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