I would like to parse a string such as p1=6&p2=7&p3=8
into a NameValueCollection
.
What is the most elegant way of doing this when you don't have access to the Page.Request
object?
I would like to parse a string such as p1=6&p2=7&p3=8
into a NameValueCollection
.
What is the most elegant way of doing this when you don't have access to the Page.Request
object?
There's a built-in .NET utility for this: HttpUtility.ParseQueryString
You may need to replace
querystring
withnew Uri(fullUrl).Query
.This is my code, I think it's very useful:
If you want to avoid the dependency on System.Web that is required to use HttpUtility.ParseQueryString, you could use the
Uri
extension methodParseQueryString
found inSystem.Net.Http
.Make sure to add a reference (if you haven't already) to
System.Net.Http
in your project.Note that you have to convert the response body to a valid
Uri
so thatParseQueryString
(inSystem.Net.Http
)works.If you don't want the System.Web dependency, just paste this source code from HttpUtility class.
I just whipped this together from the source code of Mono. It contains the HttpUtility and all it's dependencies (like IHtmlString, Helpers, HttpEncoder, HttpQSCollection).
Then use
HttpUtility.ParseQueryString
.https://gist.github.com/bjorn-ali-goransson/b04a7c44808bb2de8cca3fc9a3762f9c
I wanted to remove the dependency on System.Web so that I could parse the query string of a ClickOnce deployment, while having the prerequisites limited to the "Client-only Framework Subset".
I liked rp's answer. I added some additional logic.
HttpUtility.ParseQueryString(Request.Url.Query)
return isHttpValueCollection
(internal class). It inherits fromNameValueCollection
.