How to Build a Query String For a Url in C#

How to build a query string for a URL in C#?

If you look under the hood the QueryString property is a NameValueCollection. When I've done similar things I've usually been interested in serialising AND deserialising so my suggestion is to build a NameValueCollection up and then pass to:

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

private string ToQueryString(NameValueCollection nvc)
{
var array = (
from key in nvc.AllKeys
from value in nvc.GetValues(key)
select string.Format(
"{0}={1}",
HttpUtility.UrlEncode(key),
HttpUtility.UrlEncode(value))
).ToArray();
return "?" + string.Join("&", array);
}

I imagine there's a super elegant way to do this in LINQ too...

Build url string using C#

Use the UriBuilder class. It will ensure the resulting URI is correctly formatted.

Build query string for System.Net.HttpClient get

If I wish to submit a http get request using System.Net.HttpClient
there seems to be no api to add parameters, is this correct?

Yes.

Is there any simple api available to build the query string that
doesn't involve building a name value collection and url encoding
those and then finally concatenating them?

Sure:

var query = HttpUtility.ParseQueryString(string.Empty);
query["foo"] = "bar<>&-baz";
query["bar"] = "bazinga";
string queryString = query.ToString();

will give you the expected result:

foo=bar%3c%3e%26-baz&bar=bazinga

You might also find the UriBuilder class useful:

var builder = new UriBuilder("http://example.com");
builder.Port = -1;
var query = HttpUtility.ParseQueryString(builder.Query);
query["foo"] = "bar<>&-baz";
query["bar"] = "bazinga";
builder.Query = query.ToString();
string url = builder.ToString();

will give you the expected result:

http://example.com/?foo=bar%3c%3e%26-baz&bar=bazinga

that you could more than safely feed to your HttpClient.GetAsync method.

Best way to append query string parameter to URL from object

I got this extension method.. No need to generate query string manually.Only class object we need to pass. i thought some one else can use the same thing ...

public static string AppendObjectToQueryString(string uri, object requestObject)
{
var type = requestObject.GetType();
var data = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.ToDictionary
(
p => p.Name,
p => p.GetValue(requestObject)
);

foreach (var d in data)
{
if (d.Value == null)
{
continue;
}

if ((d.Value as string == null) && d.Value is IEnumerable enumerable)
{
foreach (var value in enumerable)
{
uri = QueryHelpers.AddQueryString(uri, d.Key, value.ToString());
}
}
else
{
uri = QueryHelpers.AddQueryString(uri, d.Key, d.Value.ToString());
}
}

return uri;
}

Ex: In my case i called this way.

string uri = "Menu/GetMenus";
string full_uri = QueryStringExtension.AppendObjectToQueryString(uri, paging);

How do I send a URL with Query Strings as a Query String

You must encode the url that you pass as a parameter in your redirect URL. Like this:

MyURL = "MyURL1?redi=" + Server.UrlEncode("MyURL2?name=me&ID=123");

This will create a correct url without the double '?' and '&' characters:

MyURL1?redi=MyURL2%3fname%3dme%26ID%3d123

See MSDN: HttpServerUtility.UrlEncode Method

To extract your redirect url from this encoded url you must use HttpServerUtility.UrlDecode to turn it into a correct url again.

compose a query URL string

Building a query string from a dictionary should be fairly straightforward - you dont need to treat the start position and the rest of the params separately.

var queryString = "?" + String.Join("&", 
myDictionary.Select(kv => String.Concat(kv.Key,"=",kv.Value)));

You may need to UrlEncode the values, depending on what they contain.

How to add or update query string parameters to given URL?

I wrote the following function which used in order to accomplish the required functionality :

        /// <summary>
/// Get URL With QueryString Dynamically
/// </summary>
/// <param name="url">URI With/Without QueryString</param>
/// <param name="newQueryStringArr">New QueryString To Append</param>
/// <returns>Return Url + Existing QueryString + New/Modified QueryString</returns>
public string BuildQueryStringUrl(string url, string[] newQueryStringArr)
{
string plainUrl;
var queryString = string.Empty;

var newQueryString = string.Join("&", newQueryStringArr);

if (url.Contains("?"))
{
var index = url.IndexOf('?');
plainUrl = url.Substring(0, index); //URL With No QueryString
queryString = url.Substring(index + 1);
}
else
{
plainUrl = url;
}

var nvc = HttpUtility.ParseQueryString(queryString);
var qscoll = HttpUtility.ParseQueryString(newQueryString);

var queryData = string.Join("&",
nvc.AllKeys.Where(key => !qscoll.AllKeys.Any(newKey => newKey.Contains(key))).
Select(key => string.Format("{0}={1}",
HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key]))).ToArray());
//Fetch Existing QueryString Except New QueryString

var delimiter = nvc.HasKeys() && !string.IsNullOrEmpty(queryData) ? "&" : string.Empty;
var queryStringToAppend = "?" + newQueryString + delimiter + queryData;

return plainUrl + queryStringToAppend;
}

Function Usage -

Suppose given url is - http://example.com/Test.aspx?foo=bar&id=100

And you want to change foo value to chart and also you want to add new query string say hello = world and testStatus = true then -

Input to Method Call :

BuildQueryStringUrl("http://example.com/Test.aspx?foo=bar&id=100",
new[] {"foo=chart", "hello=world", "testStatus=true"});

Output : http://example.com/Test.aspx?foo=chart&hello=world&testStatus=true&id=100

Hope this helps.

How to build a query string for a URL in C#?

If you look under the hood the QueryString property is a NameValueCollection. When I've done similar things I've usually been interested in serialising AND deserialising so my suggestion is to build a NameValueCollection up and then pass to:

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

private string ToQueryString(NameValueCollection nvc)
{
var array = (
from key in nvc.AllKeys
from value in nvc.GetValues(key)
select string.Format(
"{0}={1}",
HttpUtility.UrlEncode(key),
HttpUtility.UrlEncode(value))
).ToArray();
return "?" + string.Join("&", array);
}

I imagine there's a super elegant way to do this in LINQ too...

Send Query String of Current View/URL to another Action

i reached my goal with sending current URL QueryString part with Form submit Part
here is the code:

@using (Html.BeginForm("EditSubmit", "Home", new {userId = Request.QueryString["userId"]}, FormMethod.Post))
{
<input type="submit" value="Save" class="btn btn-success btn-sm" />
}

here is the main part

Request.QueryString["userId"] (inside view)


Related Topics



Leave a reply



Submit