Most optimal way to parse querystring within a str

2019-01-22 06:36发布

I have a querystring alike value set in a plain string. I started to split string to get value out but I started to wonder that I can proabably write this in one line instead. Could you please advice if there is more optimal way to do this?

I am trying to read "123" and "abc" like in Request.QueryString but from normal string.

 protected void Page_Load(object sender, EventArgs e)
{
    string qs = "id=123&xx=abc";
    string[] urlInfo = qs.Split('&');
    string id = urlInfo[urlInfo.Length - 2];
    Response.Write(id.ToString());

}

3条回答
一纸荒年 Trace。
2楼-- · 2019-01-22 07:17

Look at HttpUtility.ParseQueryString. Don't reinvent the wheel.

查看更多
三岁会撩人
3楼-- · 2019-01-22 07:21

RichardOD is on it with HttpUtility.ParseQueryString but don't forget to look at TryParse.

You can TryParse int, DateTimes etc

How do you test your Request.QueryString[] variables?

查看更多
我命由我不由天
4楼-- · 2019-01-22 07:34

You can do it this way:

using System.Collections.Specialized;

NameValueCollection query = HttpUtility.ParseQueryString(queryString);
Response.Write(query["id"]);

Hope it helps.

查看更多
登录 后发表回答