48

在 POST/GET 请求之后,我得到了我需要解析的 URL,当然我可以去使用 spit() 来获取所需的信息,但肯定应该是更优雅的方式。有任何想法吗?

http://api.vkontakte.ru/blank.html#access_token=8860213c0a392ba0971fb35bdfb0z605d459a9dcf9d2208ab60e714c3367681c6d091aa12a3fdd31a4872&expires_in=86400&user_id=34558123

我正在解析:access tokenexpires_in

4

3 回答 3

60

使用URI类,您可以执行以下操作:

var url = new Uri("your url");
于 2013-03-30T00:37:06.890 回答
50

使用 Uri + ParseQueryString 函数:

Uri myUri = new Uri("http://api.vkontakte.ru/blank.html#access_token=8860213c0a392ba0971fb35bdfb0z605d459a9dcf9d2208ab60e714c3367681c6d091aa12a3fdd31a4872&expires_in=86400&user_id=34558123");

String access_token = HttpUtility.ParseQueryString(myUri.Query).Get("access_token");
String expires_in = HttpUtility.ParseQueryString(myUri.Query).Get("expires_in");

这也可以解决问题

String access_token = HttpUtility.ParseQueryString(myUri.Query).Get(0);

来源:https ://msdn.microsoft.com/en-us/library/ms150046.aspx

提示:您可能需要

using System.Web;

并添加对 System.Web 的引用

于 2015-04-03T15:01:44.393 回答
18

There are several ways you can do this. One is that you can simply use the Uri.Query method to get the query string and then parse by the &s. Another is that you can use the Uri.Query method and then use HttpUtility.ParseQueryString to parse the query string as a NameValueCollection, which might be your preferred route.

See the example below:

using System.Web; // For HttpUtility

// The original URL:
Uri unparsedUrl = new Uri("http://api.vkontakte.ru/blank.html#access_token=8860213c0a392ba0971fb35bdfb0z605d459a9dcf9d2208ab60e714c3367681c6d091aa12a3fdd31a4872&expires_in=86400&user_id=34558123");
// Grabs the query string from the URL:
string query = unparsedUrl.Query; 
// Parses the query string as a NameValueCollection:
var queryParams = HttpUtility.ParseQueryString(query);

You can now perform operations similar to how you would deal with a Dictionary object. Like so:

string accessToken = queryParams["access_token"];
string expiresIn = queryParams["expires_in"];

This has the same functionality as what @Jeroen Bouman showed, but splits apart the different functions so you can understand what each piece does individually.

References:

Uri.Query

HttpUtility.ParseQueryString

NameValueCollection

于 2016-03-15T16:09:41.640 回答