我有一组类似于下面列表中的url

http://somesite.example/backup/lol.php?id=1&server=4&location=us http://somesite.example/news.php?article=1&lang=en

我已经设法获得查询字符串使用以下代码:

myurl = longurl.Split('?');
NameValueCollection qs = HttpUtility.ParseQueryString(myurl [1]);

foreach (string lol in qs)
{
    // results will return
}

但它只返回参数 id、服务器、位置等等,基于所提供的URL。

我需要的是向现有的查询字符串添加/追加值。

例如,使用URL:

http://somesite.example/backup/index.php?action=login&attempts=1

我需要改变查询字符串参数的值:

操作 = 登录 1

尝试= 11

如您所见,我为每个值附加了“1”。我需要从一个字符串中获得一组url,其中包含不同的查询字符串,并在末尾为每个参数添加一个值&再次将它们添加到列表中。


当前回答

我将Darin的答案包装到一个可重用的扩展方法中。

public static class UriExtensions
{
    /// <summary>
    /// Adds the specified parameter to the Query String.
    /// </summary>
    /// <param name="url"></param>
    /// <param name="paramName">Name of the parameter to add.</param>
    /// <param name="paramValue">Value for the parameter to add.</param>
    /// <returns>Url with added parameter.</returns>
    public static Uri AddParameter(this Uri url, string paramName, string paramValue)
    {
        var uriBuilder = new UriBuilder(url);
        var query = HttpUtility.ParseQueryString(uriBuilder.Query);
        query[paramName] = paramValue;
        uriBuilder.Query = query.ToString();

        return uriBuilder.Uri;
    }
}

其他回答

这更令人沮丧,因为现在(.net 5) MS已经标记了许多(所有)他们的方法,接受字符串而不是Uri为过时。

不管怎样,操纵相对uri的更好方法可能是给它它想要的东西:

var requestUri = new Uri("x://x").MakeRelativeUri(
   new UriBuilder("x://x") { Path = path, Query = query }.Uri);

您可以使用其他答案实际构建查询字符串。

注意,你可以添加微软的Microsoft. aspnetcore . webutilities nuget包,然后用它来附加值到查询字符串:

QueryHelpers.AddQueryString(longurl, "action", "login1")
QueryHelpers.AddQueryString(longurl, new Dictionary<string, string> { { "action", "login1" }, { "attempts", "11" } });

结束了所有URL查询字符串编辑的麻烦

在对Uri类和其他解决方案进行了大量的辛劳和摆弄之后,下面是我的字符串扩展方法来解决我的问题。

using System;
using System.Collections.Specialized;
using System.Linq;
using System.Web;

public static class StringExtensions
{
    public static string AddToQueryString(this string url, params object[] keysAndValues)
    {
        return UpdateQueryString(url, q =>
        {
            for (var i = 0; i < keysAndValues.Length; i += 2)
            {
                q.Set(keysAndValues[i].ToString(), keysAndValues[i + 1].ToString());
            }
        });
    }

    public static string RemoveFromQueryString(this string url, params string[] keys)
    {
        return UpdateQueryString(url, q =>
        {
            foreach (var key in keys)
            {
                q.Remove(key);
            }
        });
    }

    public static string UpdateQueryString(string url, Action<NameValueCollection> func)
    {
        var urlWithoutQueryString = url.Contains('?') ? url.Substring(0, url.IndexOf('?')) : url;
        var queryString = url.Contains('?') ? url.Substring(url.IndexOf('?')) : null;
        var query = HttpUtility.ParseQueryString(queryString ?? string.Empty);

        func(query);

        return urlWithoutQueryString + (query.Count > 0 ? "?" : string.Empty) + query;
    }
}

我喜欢Bjorn的答案,但他提供的解决方案是误导性的,因为该方法更新一个现有的参数,而不是添加它,如果它不存在。为了更安全一点,我在下面对它进行了修改。

public static class UriExtensions
{
    /// <summary>
    /// Adds or Updates the specified parameter to the Query String.
    /// </summary>
    /// <param name="url"></param>
    /// <param name="paramName">Name of the parameter to add.</param>
    /// <param name="paramValue">Value for the parameter to add.</param>
    /// <returns>Url with added parameter.</returns>
    public static Uri AddOrUpdateParameter(this Uri url, string paramName, string paramValue)
    {
        var uriBuilder = new UriBuilder(url);
        var query = HttpUtility.ParseQueryString(uriBuilder.Query);

        if (query.AllKeys.Contains(paramName))
        {
            query[paramName] = paramValue;
        }
        else
        {
            query.Add(paramName, paramValue);
        }
        uriBuilder.Query = query.ToString();

        return uriBuilder.Uri;
    }
}

下面的解决方案适用于ASP。NET 5 (vNext),它使用QueryHelpers类来构建带有参数的URI。

    public Uri GetUri()
    {
        var location = _config.Get("http://iberia.com");
        Dictionary<string, string> values = GetDictionaryParameters();

        var uri = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(location, values);
        return new Uri(uri);
    }

    private Dictionary<string,string> GetDictionaryParameters()
    {
        Dictionary<string, string> values = new Dictionary<string, string>
        {
            { "param1", "value1" },
            { "param2", "value2"},
            { "param3", "value3"}
        };
        return values;
    }

结果URI应该是http://iberia.com?param1=value1&param2=value2&param3=value3