且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中的URL获得字符串或者字符串的一部分

更新时间:2022-10-22 10:51:29


  

我使用字符串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
}

然后你可以使用 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 and Substring to get the desired code BUT what if the userid or comment also has = symbol and & symbol then my IndexOf will return number and my Substring 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 a string Uri, instead use the Url 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 use Uri 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);