从 Uri 获取单独的查询参数

发布于 2024-09-02 20:53:40 字数 352 浏览 3 评论 0原文

我有一个 uri 字符串,例如: http://example.com/ file?a=1&b=2&c=string%20param

是否有一个现有函数可以将查询参数字符串转换为字典,就像 ASP.NET Context.Request 那样。

我正在编写一个控制台应用程序而不是一个 Web 服务,因此没有 Context.Request 来为我解析 URL。

我知道自己破解查询字符串非常容易,但我宁愿使用 FCL 函数 is ifexists。

I have a uri string like: http://example.com/file?a=1&b=2&c=string%20param

Is there an existing function that would convert query parameter string into a dictionary same way as ASP.NET Context.Request does it.

I'm writing a console app and not a web-service so there is no Context.Request to parse the URL for me.

I know that it's pretty easy to crack the query string myself but I'd rather use a FCL function is if exists.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

骄傲 2024-09-09 20:53:40

使用这个:

string uri = ...;
string queryString = new System.Uri(uri).Query;
var queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString);

Tejs 的这段代码不是从 URI 获取查询字符串的“正确”方法:

string.Join(string.Empty, uri.Split('?').Skip(1));

Use this:

string uri = ...;
string queryString = new System.Uri(uri).Query;
var queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString);

This code by Tejs isn't the 'proper' way to get the query string from the URI:

string.Join(string.Empty, uri.Split('?').Skip(1));
魔法唧唧 2024-09-09 20:53:40

您可以使用:

var queryString = url.Substring(url.IndexOf('?')).Split('#')[0]
System.Web.HttpUtility.ParseQueryString(queryString)

MSDN

You can use:

var queryString = url.Substring(url.IndexOf('?')).Split('#')[0]
System.Web.HttpUtility.ParseQueryString(queryString)

MSDN

烟燃烟灭 2024-09-09 20:53:40

这应该有效:

string url = "http://example.com/file?a=1&b=2&c=string%20param";
string querystring = url.Substring(url.IndexOf('?'));
System.Collections.Specialized.NameValueCollection parameters = 
   System.Web.HttpUtility.ParseQueryString(querystring);

根据 MSDN。不是您正在寻找的确切集合类型,但仍然有用。

编辑:显然,如果您向 ParseQueryString 提供完整的网址,它将添加 'http://example.com/file?a' 作为集合的第一个键。由于这可能不是您想要的,因此我添加了子字符串以仅获取网址的相关部分。

This should work:

string url = "http://example.com/file?a=1&b=2&c=string%20param";
string querystring = url.Substring(url.IndexOf('?'));
System.Collections.Specialized.NameValueCollection parameters = 
   System.Web.HttpUtility.ParseQueryString(querystring);

According to MSDN. Not the exact collectiontype you are looking for, but nevertheless useful.

Edit: Apparently, if you supply the complete url to ParseQueryString it will add 'http://example.com/file?a' as the first key of the collection. Since that is probably not what you want, I added the substring to get only the relevant part of the url.

一萌ing 2024-09-09 20:53:40

我必须为现代 Windows 应用程序执行此操作。我使用了以下内容:

public static class UriExtensions
{
    private static readonly Regex _regex = new Regex(@"[?&](\w[\w.]*)=([^?&]+)");

    public static IReadOnlyDictionary<string, string> ParseQueryString(this Uri uri)
    {
        var match = _regex.Match(uri.PathAndQuery);
        var paramaters = new Dictionary<string, string>();
        while (match.Success)
        {
            paramaters.Add(match.Groups[1].Value, match.Groups[2].Value);
            match = match.NextMatch();
        }
        return paramaters;
    }
}

I had to do this for a modern windows app. I used the following:

public static class UriExtensions
{
    private static readonly Regex _regex = new Regex(@"[?&](\w[\w.]*)=([^?&]+)");

    public static IReadOnlyDictionary<string, string> ParseQueryString(this Uri uri)
    {
        var match = _regex.Match(uri.PathAndQuery);
        var paramaters = new Dictionary<string, string>();
        while (match.Success)
        {
            paramaters.Add(match.Groups[1].Value, match.Groups[2].Value);
            match = match.NextMatch();
        }
        return paramaters;
    }
}
夜深人未静 2024-09-09 20:53:40

看一下 HttpUtility.ParseQueryString()它会给你一个 NameValueCollection 而不是字典,但仍然应该做你需要的事情。

另一种选择是使用string.Split()

    string url = @"http://example.com/file?a=1&b=2&c=string%20param";
    string[] parts = url.Split(new char[] {'?','&'});
    ///parts[0] now contains http://example.com/file
    ///parts[1] = "a=1"
    ///parts[2] = "b=2"
    ///parts[3] = "c=string%20param"

Have a look at HttpUtility.ParseQueryString() It'll give you a NameValueCollection instead of a dictionary, but should still do what you need.

The other option is to use string.Split().

    string url = @"http://example.com/file?a=1&b=2&c=string%20param";
    string[] parts = url.Split(new char[] {'?','&'});
    ///parts[0] now contains http://example.com/file
    ///parts[1] = "a=1"
    ///parts[2] = "b=2"
    ///parts[3] = "c=string%20param"
梦归所梦 2024-09-09 20:53:40

对于孤立的项目,依赖关系必须保持在最低限度,我发现自己使用这个实现:

var arguments = uri.Query
  .Substring(1) // Remove '?'
  .Split('&')
  .Select(q => q.Split('='))
  .ToDictionary(q => q.FirstOrDefault(), q => q.Skip(1).FirstOrDefault());

但是请注意,我处理任何类型的编码字符串,因为我在一个受控设置,其中编码问题将是服务器端的编码错误,应予以修复。

For isolated projects, where dependencies must be kept to a minimum, I found myself using this implementation:

var arguments = uri.Query
  .Substring(1) // Remove '?'
  .Split('&')
  .Select(q => q.Split('='))
  .ToDictionary(q => q.FirstOrDefault(), q => q.Skip(1).FirstOrDefault());

Do note, however, that I do not handle encoded strings of any kind, as I was using this in a controlled setting, where encoding issues would be a coding error on the server side that should be fixed.

×纯※雪 2024-09-09 20:53:40

在一行代码中:

string xyz = Uri.UnescapeDataString(HttpUtility.ParseQueryString(Request.QueryString.ToString()).Get("XYZ"));

In a single line of code:

string xyz = Uri.UnescapeDataString(HttpUtility.ParseQueryString(Request.QueryString.ToString()).Get("XYZ"));
缺⑴份安定 2024-09-09 20:53:40

您可以在控制台应用程序中引用 System.Web,然后查找拆分 URL 参数的实用程序函数。

You could reference System.Web in your console application and then look for the Utility functions that split the URL parameters.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文