I know i can do this
var nv = HttpUtility.ParseQueryString(req.RawUrl);
But is there a way to convert this back to a url?
var newUrl = HttpUtility.Something("/page", nv);
I know i can do this
var nv = HttpUtility.ParseQueryString(req.RawUrl);
But is there a way to convert this back to a url?
var newUrl = HttpUtility.Something("/page", nv);
In AspNet Core 2.0 you can use QueryHelpers AddQueryString method.
This should work without too much code:
The idea is to use
HttpUtility.ParseQueryString
to generate an empty collection of typeHttpValueCollection
. This class is a subclass ofNameValueCollection
that is marked asinternal
so that your code cannot easily create an instance of it.The nice thing about
HttpValueCollection
is that theToString
method takes care of the encoding for you. By leveraging theNameValueCollection.Add(NameValueCollection)
method, you can add the existing query string parameters to your newly created object without having to first convert theRequest.QueryString
collection into a url-encoded string, then parsing it back into a collection.This technique can be exposed as an extension method as well:
Would this work for you?
Use:
Make an extension method that uses a couple of loops. I prefer this solution because it's readable (no linq), doesn't require System.Web.HttpUtility, and it handles duplicate keys.
Example
Output
You can use.
if this nv is of type string you can append to the uri first parameter. Like