替代HttpUtility.ParseQueryString没有的System.Web依赖? [英] Alternative to HttpUtility.ParseQueryString without System.Web dependency?

查看:746
本文介绍了替代HttpUtility.ParseQueryString没有的System.Web依赖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够只需添加的键值对一些辅助类来构建URL查询字符串,并使其返回这个作为URL查询。我知道这是可以做到,像这样:

I want to be able to build URL query strings by just adding the key and value to some helper class and have it return this as a URL query. I know this can be done, like so:

var queryBuilder= HttpUtility.ParseQueryString("http://baseurl.com/?");
queryBuilder.Add("Key", "Value");
string url =  queryBuilder.ToString();



这正是我追求的行为。然而,这个类在著名的大型存在的System.Web ,我宁愿不把那个整个图书馆在此。是否有其他地方?

Which is exactly the behaviour I'm after. However, this class exists in the famously large System.Web and I'd rather not bring that whole library in for this. Is there an alternative somewhere?

推荐答案

您正在使用您的示例中的HttpValueCollection其实不是小事,并利用大量的对System.Web库的其他部分进行编码的有效的HTTP URL为您服务。它可以提取您需要的部分源代码,但它可能会级联成颇有几分比你想象的多!

The HttpValueCollection you're using in your example is not actually trivial, and makes use of plenty of other parts of the System.Web library to encode a valid http url for you. It is possible to extract the source for the parts you need, but it would likely cascade into quite a bit more than you think!

如果你明白这一点,只是想要的东西原始的,因为你已经确保键和值正确编码,最容易做的事情将是刚刚推出自己的。

If you understand that and simply want something primitive because you already ensure that the keys and values are encoded correctly, the easiest thing to do would be to just roll your own.

下面是一个例子,在形式扩展方法来NameValueCollection中:

Here's an example, in the form of an extension method to NameValueCollection:

public static class QueryExtensions
{
    public static string ToQueryString(this NameValueCollection nvc)
    {
        IEnumerable<string> segments = from key in nvc.AllKeys
                                       from value in nvc.GetValues(key)
                                       select string.Format("{0}={1}", key, value);
        return "?" + string.Join("&", segments);
    }
}

您可以使用这个扩展建立一个查询字符串所以:

You could use this extension to build a query string like so:

// Initialise the collection with values.
var values = new NameValueCollection {{"Key1", "Value1"}, {"Key2", "Value2"}};

// Or use the Add method, if you prefer.
values.Add("Key3", "Value3");

// Build a Uri using the extension method.
var url = new Uri("http://baseurl.com/" + values.ToQueryString());

这篇关于替代HttpUtility.ParseQueryString没有的System.Web依赖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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