Convert a Dictionary to string of url parameters?

≡放荡痞女 提交于 2020-12-08 05:18:16

问题


Is there a way to convert a Dictionary in code into a url parameter string?

e.g.

// An example list of parameters
Dictionary<string, object> parameters ...;
foreach (Item in List)
{
    parameters.Add(Item.Name, Item.Value);
}

string url = "http://www.somesite.com?" + parameters.XX.ToString();

Inside MVC HtmlHelpers you can generate URLs with the UrlHelper (or Url in controllers) but in Web Forms code-behind the this HtmlHelper is not available.

string url = UrlHelper.GenerateUrl("Default", "Action", "Controller", 
    new RouteValueDictionary(parameters), htmlHelper.RouteCollection , 
    htmlHelper.ViewContext.RequestContext, true);

How could this be done in C# Web Forms code-behind (in an MVC/Web Forms app) without the MVC helper?


回答1:


One approach would be:

var url = string.Format("http://www.yoursite.com?{0}",
    HttpUtility.UrlEncode(string.Join("&",
        parameters.Select(kvp =>
            string.Format("{0}={1}", kvp.Key, kvp.Value)))));

You could also use string interpolation as introduced in C#6:

var url = $"http://www.yoursite.com?{HttpUtility.UrlEncode(string.Join("&", parameters.Select(kvp => $"{kvp.Key}={kvp.Value}")))}";

And you could get rid of the UrlEncode if you don't need it, I just added it for completeness.




回答2:


Make a static helper class perhaps:

public static string QueryString(IDictionary<string, object> dict)
{
    var list = new List<string>();
    foreach(var item in dict)
    {
        list.Add(item.Key + "=" + item.Value);
    }
    return string.Join("&", list);
}



回答3:


You can use QueryHelpers from Microsoft.AspNetCore.WebUtilities:

string url = QueryHelpers.AddQueryString("https://me.com/xxx.js", dictionary);



回答4:


the most short way:

string s = string.Join("&", dd.Select((x) => x.Key + "=" + x.Value.ToString()));

But shorter does not mean more efficiency. Better use StringBuilder and Append method:

first = true;
foreach(var item in dd)
{
    if (first)
        first = false;
    else
        sb.Append('&');
    sb.Append(item.Key);
    sb.Append('=');
    sb.Append(item.Value.ToString());
}



回答5:


You could use a IEnumerable<string> and String.Join:

var parameters = new List<string>();
foreach (var item in List)
{
    parameters.Add(item.Name + "=" + item.Value.ToString());
}

string url = "http://www.somesite.com?" + String.Join("&", parameters);

or shorter

string baseUri = "http://www.somesite.com?";
string url = baseUri + String.Join("&", list.Select(i => $"{i.Name}={i.Value}"));



回答6:


I have written these extensions methods:

Add querystring to base url:

public static string AddQueryString(this string url, IDictionary<string, object> parameters) => 
     $"{url}?{parameters.ToQueryString()}";

Convert dictionary of parameters to query string:

private static string ToQueryString(this IDictionary<string, object> parameters) => 
    string.Join("&", parameters.Select(x => $"{x.Key}={x.Value}"));

Actual code to convert to query string:

string.Join("&", parameters.Select(x => $"{x.Key}={x.Value}"));

Edit:

When using in production consider encoding the parameters with URL.Encode within this function. If you use this make sure the parameters in the dictionary are not already encoded.




回答7:


Is this what you looking for (untested code)?

StringBuilder sb = new StringBuilder();
sb.Append("http://www.somesite.com?");

foreach(var item in parameters)
{
sb.append(string.Format("{0}={1}&", item.Key, item.Value))
}
string finalUrl = sb.ToString();
finalUrl = finalUrl.Remove(finalUrl.LasIndexOf("&"));



回答8:


You may try this:

var parameters = new Dictionary<string, string>(); // You pass this
var url = "http://www.somesite.com?";
int i = 0;
foreach (var item in parameters)
{
    url += item.Key + "=" + item.Value;
    url += i != parameters.Count ? "&" : string.Empty;
    i++;
}

return url;

I have not run the logic, but this might help you.

If you would be UrlRouting in webforms then it would be a different story.

Check out:

http://msdn.microsoft.com/en-us/library/cc668201(v=vs.90).aspx




回答9:


You can add the following class to the project and use the extension method.

using System.Collections.Generic;
using System.Linq;
using System.Text;

public static class CollectionExtensions {
    public static string ToQueryString(this IDictionary<string, string> dict)
    {

    if (dict.Count == 0) return string.Empty;

    var buffer = new StringBuilder();
    int count = 0;
    bool end = false;

    foreach (var key in dict.Keys)
    {
        if (count == dict.Count - 1) end = true;

        if (end)
            buffer.AppendFormat("{0}={1}", key, dict[key]);
        else
            buffer.AppendFormat("{0}={1}&", key, dict[key]);

        count++;
    }

    return buffer.ToString();
}
}

to use the code:

var queryString = dictionary.ToQueryString();



回答10:


I'm not saying this option is better (I personally think it's not), but I'm here just to say it exists.

The QueryBuilder class:

var queryStringDictionary = new Dictionary<string, string>
{
    { "username", "foo" },
    { "password", "bar" }
};

var queryBuilder = new QueryBuilder(queryStringDictionary);
queryBuilder.Add("type", "user");

//?username=foo&password=bar&type=user
QueryString result = queryBuilder.ToQueryString();


来源:https://stackoverflow.com/questions/23518966/convert-a-dictionary-to-string-of-url-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!