Easiest way to parse “querystring” formatted data

后端 未结 6 1853
误落风尘
误落风尘 2020-11-29 09:11

With the following code:

string q = \"userID=16555&gameID=60&score=4542.122&time=343114\";

What would be the easiest way to par

6条回答
  •  抹茶落季
    2020-11-29 09:41

    If you want to avoid the dependency on System.Web that is required to use HttpUtility.ParseQueryString, you could use the Uri extension method ParseQueryString found in System.Net.Http.

    Note that you have to convert the response body to a valid Uri so that ParseQueryString works.

    Please also note in the MSDN document, this method is an extension method for the Uri class, so you need reference the assembly System.Net.Http.Formatting (in System.Net.Http.Formatting.dll). I tried installed it by the nuget package with the name "System.Net.Http.Formatting", and it works fine.

    string body = "value1=randomvalue1&value2=randomValue2";
    
    // "http://localhost/query?" is added to the string "body" in order to create a valid Uri.
    string urlBody = "http://localhost/query?" + body;
    NameValueCollection coll = new Uri(urlBody).ParseQueryString();
    

提交回复
热议问题