【问题标题】:How to get string from formatted url in asp.net c#如何从asp.net c#中的格式化url获取字符串
【发布时间】:2014-11-07 08:56:13
【问题描述】:

假设我们在页面www.abc.com/apple-store

那么如何在asp C#代码中获取字符串apple-store

存储到另一个变量中。

【问题讨论】:

  • 什么是“我们在页面上”?是你的页面吗?
  • @Tim 是的,假设 example.com/apple-store 我想获取这个字符串 'apple-store' 并存储到变量中。

标签: asp.net url c#-4.0 formatted


【解决方案1】:

你可以使用 string.last() 来提取它。

string lastPartUrl =HttpContext.Current.Request.Url.AbsoluteUri.Split('/').Last();

【讨论】:

  • 非常感谢。我尝试了很多但没能做到。您的解决方案有效!太棒了..上帝保佑你。
  • 很高兴能为您提供帮助 :)
【解决方案2】:

您应该使用Request.RawUrl 属性。查看更多详情here

您也可以使用Request.Url(请参阅here)属性来获取当前URL 的不同部分。例如,您将使用Request.Url.LocalPath 获得相同的结果。

【讨论】:

  • 然后按照这个答案解析:stackoverflow.com/questions/14685147/…
  • @SmartDev 'sw' 是什么。在您给出的链接中提到了这一点。我想不通。 sw.WriteLine(Server.HtmlEncode(Request.RawUrl));下面的代码示例使用 HtmlEncode 方法对 RawUrl 属性的值进行 HTML 编码,并使用 WriteLine 方法将编码后的值写入文件。此代码示例是为 HttpRequest 类提供的更大示例的一部分。
  • sw 这是StreamWriter。该示例使用它将结果写入文件。你不需要这个。只需使用string url = Request.RawUrl;
【解决方案3】:

您可以在字符串变量中获取 url。此外,您可以实现以下逻辑,将值保存在变量中。

string str = "www.abc.com/apple-store";
string result = "";
int i= 0;
int len = str.Length;

//Get the index of the character
i = str.IndexOf('/');    
//store the result in the variable
result = str.Substring(i+1,len-i-1);

Console.WriteLine("Resultant:- {0}", result);`

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    相关资源
    最近更新 更多