如何从 C# 中的 url 获取子字符串或字符串的一部分

how to get substring or part of string from a url in c#

我有一个使用 post 评论的应用程序。安全不是问题。 字符串 url = http://example.com/xyz/xyz.html?userid=xyz&comment=Comment

我想要的是从上面的字符串中提取用户标识和评论。 我尝试并发现我可以使用 IndexOfSubstring 来获取所需的代码但是如果用户 ID 或评论也有 = 符号和 & 符号那么我的 IndexOf 将 return号码和我的Substring会错。 你能帮我找到一个更合适的方法来提取用户 ID 和评论吗? 谢谢。

I got url using string url = HttpContext.Current.Request.Url.AbsoluteUri;

不要使用 AbsoluteUri 属性 ,它会给你一个 string Uri,而是直接使用 Url 属性 像:

var result = System.Web.HttpUtility.ParseQueryString(HttpContext.Current.Request.Url.Query);

然后你可以像这样提取每个参数:

Console.WriteLine(result["userid"]);
Console.WriteLine(result["comment"]);

对于其他情况,当您有 string uri 时,请不要使用字符串操作,而是使用 Uri class。

Uri uri = new Uri(@"http://example.com/xyz/xyz.html?userid=xyz&comment=Comment");

您还可以使用 TryCreate 方法,该方法在 Uri 无效时不会抛出异常。

Uri uri;
if (!Uri.TryCreate(@"http://example.com/xyz/xyz.html?userid=xyz&comment=Comment", UriKind.RelativeOrAbsolute, out uri))
{
    //Invalid Uri
}

然后你可以使用System.Web.HttpUtility.ParseQueryString获取查询字符串参数:

 var result = System.Web.HttpUtility.ParseQueryString(uri.Query);

最丑陋的方法如下:

String url = "http://example.com/xyz/xyz.html?userid=xyz&comment=Comment";
usr = url.Split('?')[1];
usr= usr.Split('&')[0];
usr = usr.Split('=')[1];

但是@habib 版本更好