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

Mia*_*mad 1 c# regex asp.net c#-4.0 asp.net-mvc-4

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

我想要的是从上面的字符串中提取用户ID和注释.我试过,发现我可以使用IndexOfSubstring获得所需的代码,但如果用户标识或注释也有=符号和符号,那么我IndexOf将返回数字,我的Substring错误.你能找到一个更合适的方法来提取用户ID和评论.谢谢.

Hab*_*bib 5

我得到了url使用字符串url = HttpContext.Current.Request.Url.AbsoluteUri;

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

var result = System.Web.HttpUtility.ParseQueryString(HttpContext.Current.Request.Url.Query);
Run Code Online (Sandbox Code Playgroud)

然后你可以提取每个参数,如:

Console.WriteLine(result["userid"]);
Console.WriteLine(result["comment"]);
Run Code Online (Sandbox Code Playgroud)

对于其他情况,当你有stringuri然后不使用字符串操作,而是使用Uri类.

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

TryCreate在无效的Uri的情况下,您也可以使用不抛出异常的方法.

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

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

 var result = System.Web.HttpUtility.ParseQueryString(uri.Query);
Run Code Online (Sandbox Code Playgroud)