C# 如何在c中从url获取子字符串或部分字符串#
我有一个应用程序,其中使用post评论。安全不是问题。 字符串url= 我想要的是从上面的字符串中提取userid和注释。 我尝试并发现我可以使用C# 如何在c中从url获取子字符串或部分字符串#,c#,asp.net,regex,asp.net-mvc-4,c#-4.0,C#,Asp.net,Regex,Asp.net Mvc 4,C# 4.0,我有一个应用程序,其中使用post评论。安全不是问题。 字符串url= 我想要的是从上面的字符串中提取userid和注释。 我尝试并发现我可以使用IndexOf和Substring来获得所需的代码,但是如果用户ID或注释也有=symbol和&symbol,那么我的IndexOf将返回数字,而我的Substring将出错。 你能帮我找到一个更合适的提取用户ID和评论的方法吗。 谢谢 我使用字符串url获取url= HttpContext.Current.Request.Url.AbsoluteUr
IndexOf
和Substring
来获得所需的代码,但是如果用户ID或注释也有=symbol和&symbol,那么我的IndexOf
将返回数字,而我的Substring
将出错。
你能帮我找到一个更合适的提取用户ID和评论的方法吗。
谢谢
我使用字符串url获取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");
您还可以使用在Uri无效的情况下不会引发异常的方法
Uri uri;
if (!Uri.TryCreate(@"http://example.com/xyz/xyz.html?userid=xyz&comment=Comment", UriKind.RelativeOrAbsolute, out uri))
{
//Invalid Uri
}
然后可以使用获取查询字符串参数:
var result = System.Web.HttpUtility.ParseQueryString(uri.Query);
我使用字符串url获取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");
您还可以使用在Uri无效的情况下不会引发异常的方法
Uri uri;
if (!Uri.TryCreate(@"http://example.com/xyz/xyz.html?userid=xyz&comment=Comment", UriKind.RelativeOrAbsolute, out uri))
{
//Invalid Uri
}
然后可以使用获取查询字符串参数:
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版本更好最丑陋的方式是:
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版本更好否。我相信,您可以从响应对象中获取它们,作为查询字符串值。可能重复No。我相信,您可以从响应对象中获取它们,作为查询字符串值。可能重复I am newbie,您能建议我如何在使用uriI后从上面的链接中提取xyz和注释吗?我使用字符串url=HttpContext.Current.Request.url.AbsoluteUri获取url;现在我做Uri=newuri(@url);var result=System.Web.HttpUtility.ParseQueryString(uri.Query);记住,当你需要它时,它总是在那里。@Asbat,那太好了,不要使用
AbsoluteUri
,而是直接使用Url
,而不要将其转换为字符串。@Asbat,我已经修改了答案我是新手,您能建议我如何在使用uriI后从上面的链接中提取xyz和注释吗?我使用字符串url=HttpContext.Current.Request.url.AbsoluteUri获取url;现在我做Uri=newuri(@url);var result=System.Web.HttpUtility.ParseQueryString(uri.Query);记住,当你需要它时,它总是在那里。@Asbat,那太好了,不要使用AbsoluteUri
,而是直接使用Url
,而不要将其转换为字符串。@Asbat,我已经修改了答案,但正如我的问题所说,如果用户id或注释包含?&=这将是一个无效的url,但正如我的问题所说,如果用户id或注释包含?&=那将是一个无效的url