如何建立在C#中的URL的查询字符串? [英] How to build a query string for a URL in C#?

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

问题描述

当从code调用网络资源是建设一个查询字符串包括所有必要的参数的共同任务。虽然通过各种手段没有火箭科学,也有一些漂亮的细节,你需要照顾好喜欢的,附加的&安培; 如果不是第一个参数,编码参数等。

A common task when calling web resources from a code is building a query string to including all the necessary parameters. While by all means no rocket science, there are some nifty details you need to take care of like, appending an & if not the first parameter, encoding the parameters etc.

在code做到这一点很简单,但有点乏味:

The code to do it is very simple, but a bit tedious:

StringBuilder SB = new StringBuilder();
if (NeedsToAddParameter A) 
{ 
  SB.Append("A="); SB.Append(HttpUtility.UrlEncode("TheValueOfA")); 
}

if (NeedsToAddParameter B) 
{
  if (SB.Length>0) SB.Append("&"); 
  SB.Append("B="); SB.Append(HttpUtility.UrlEncode("TheValueOfB")); }
}

这是这样一个共同的任务,人们所期望的一个实用工具类存在,使得它更加优雅和可读性。扫描MSDN,我没能找到一个—这使我想到了以下问题:

This is such a common task one would expect a utility class to exist that makes it more elegant and readable. Scanning MSDN, I failed to find one—which brings me to the following question:

什么是你知道做上述的最优雅干净的方式?

What is the most elegant clean way you know of doing the above?

推荐答案

如果你看看引擎盖下的查询字符串属性是一个NameValueCollection中。当我做过类似的事情,我平时一直感兴趣的连载和deserialising所以我的建议是建立一个的NameValueCollection起来,然后传递到:

If you look under the hood the QueryString property is a NameValueCollection. When I've done similar things I've usually been interested in serialising AND deserialising so my suggestion is to build a NameValueCollection up and then pass to:

using System.Web;
using System.Collections.Specialized;

private string ToQueryString(NameValueCollection nvc)
{
    var array = (from key in nvc.AllKeys
        from value in nvc.GetValues(key)
        select string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value)))
        .ToArray();
    return "?" + string.Join("&", array);
}

也许我可能已经格式化的更好:)

Possibly I could've formatted that better :)

我想有一个超级优雅的方式在LINQ做到这一点太...

I imagine there's a super elegant way to do this in LINQ too...

这篇关于如何建立在C#中的URL的查询字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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