如何在C#中的URL获得字符串或者字符串的一部分 [英] how to get substring or part of string from a url in c#
问题描述
我在这里使用发表评论的应用程序。安全是不是一个问题。
字符串的URL = http://example.com/xyz/xyz.html?用户id = XYZ和放大器;注释=注释
我要的是提取上面的字符串的用户ID和注释。
我想,我发现我可以用的IndexOf
和子串
来获得所需的code,但如果用户标识或评论也有符号=和&安培;符号那么我的的IndexOf
将返回号码和我的子串
将是错误的。
你可以请找我解压的用户ID和评论更合适的方式。
谢谢你。
我使用字符串URL得到URL =
HttpContext.Current.Request.Url.AbsoluteUri;
块引用>不要使用
绝对URI
属性,它会给你一个字符串
开放的,而不是使用网址
属性直接,如:VAR的结果= System.Web.HttpUtility.ParseQueryString(HttpContext.Current.Request.Url.Query);
然后就可以像提取每个参数:
Console.WriteLine(结果[将把userid]);
Console.WriteLine(结果[意见]);有关其他情况下,当你有
字符串
URI那么就不要使用字符串操作,而是使用乌里
类。开放的URI =新的URI(@http://example.com/xyz/xyz.html?userid=xyz&comment=Comment);
您也可以使用
TryCreate
,它并不在乌里无效的情况下,抛出的异常的方法。开放的URI;
如果(!Uri.TryCreate(@http://example.com/xyz/xyz.html?userid=xyz&comment=Comment,UriKind.RelativeOrAbsolute,出URI))
{
//无效的URI
}然后你可以使用<一个href=\"https://msdn.microsoft.com/en-us/library/system.web.httputility.parsequerystring%28v=vs.110%29.aspx\"相对=nofollow>
System.Web.HttpUtility.ParseQueryString
获取查询字符串参数:VAR的结果= System.Web.HttpUtility.ParseQueryString(uri.Query);
I have an application where uses post comments. Security is not an issue. string url = http://example.com/xyz/xyz.html?userid=xyz&comment=Comment
What i want is to extract the userid and comment from above string. I tried and found that i can use
IndexOf
andSubstring
to get the desired code BUT what if the userid or comment also has = symbol and & symbol then myIndexOf
will return number and mySubstring
will be wrong. Can you please find me a more suitable way of extracting userid and comment. Thanks.解决方案I got url using string url = HttpContext.Current.Request.Url.AbsoluteUri;
Do not use
AbsoluteUri
property , it will give you astring
Uri, instead use theUrl
property directly like:var result = System.Web.HttpUtility.ParseQueryString(HttpContext.Current.Request.Url.Query);
and then you can extract each parameter like:
Console.WriteLine(result["userid"]); Console.WriteLine(result["comment"]);
For other cases when you have
string
uri then do not use string operations, instead useUri
class.Uri uri = new Uri(@"http://example.com/xyz/xyz.html?userid=xyz&comment=Comment");
You can also use
TryCreate
method which doesn't throw exception in case of invalid Uri.Uri uri; if (!Uri.TryCreate(@"http://example.com/xyz/xyz.html?userid=xyz&comment=Comment", UriKind.RelativeOrAbsolute, out uri)) { //Invalid Uri }
and then you can use
System.Web.HttpUtility.ParseQueryString
to get query string parameters:var result = System.Web.HttpUtility.ParseQueryString(uri.Query);
这篇关于如何在C#中的URL获得字符串或者字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!