Home >Backend Development >C++ >How to Extract URL Parameters from a String in .NET?
Problem:
Given a URL string in a .NET application, how can you easily extract the value of a specific parameter without relying on the Request.Params
property?
Solution:
The most straightforward approach is using the System.Web.HttpUtility.ParseQueryString
method. This static method parses the query string portion of a URL and returns a NameValueCollection
, allowing easy access to parameter values. Here's how:
<code class="language-csharp">Uri myUri = new Uri("http://www.example.com?param1=good¶m2=bad"); string param1Value = HttpUtility.ParseQueryString(myUri.Query).Get("param1"); </code>
This code snippet first creates a Uri
object from the URL string. Then, it uses ParseQueryString
on the Query
property of the Uri
(which contains the parameters) to get a NameValueCollection
. Finally, the Get("param1")
method retrieves the value associated with the "param1" parameter.
For comprehensive details and further examples, consult the official Microsoft documentation: https://www.php.cn/link/29a83a8a9641bb860a679d7e5ba52d26 (Note: This link may be outdated; search for "HttpUtility.ParseQueryString" on the current Microsoft documentation site for the most up-to-date information).
The above is the detailed content of How to Extract URL Parameters from a String in .NET?. For more information, please follow other related articles on the PHP Chinese website!