如何在C#中的URL获得字符串或者字符串的一部分 [英] how to get substring or part of string from a url in c#

查看:525
本文介绍了如何在C#中的URL获得字符串或者字符串的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里使用发表评论的应用程序。安全是不是一个问题。
字符串的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 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);

这篇关于如何在C#中的URL获得字符串或者字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆