防止C#在查询字符串中编码括号 [英] Prevent C# from encoding brackets in query string

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

问题描述

我需要使用一个带有名为names []的GET参数的服务。

I need to consume a service that takes a GET parameter named "names[]".

例如: GET http://example.com/name2id?names [] = john

For example: GET http://example.com/name2id?names[]=john

当我尝试使用WebClient在C#中使用它时,括号被编码为%5B%5D,服务器无法理解。当我使用我的浏览器(未编码)发送上述内容时,一切正常。

When I try to consume that in C# using a WebClient, the brackets gets encoded to %5B%5D, which the servies does not understand. When I send the above using my browser (un-encoded), everything works fine.

下面是不起作用的示例:

Heres the example that does not work:

using (var client = new System.Net.WebClient())
{
    response = client.DownloadString(new Uri("http://example.com/name2id?names[]=john"));
}

由fiddler监控,继承人请求:

Monitored by fiddler, heres the request:

GET http://example.com/name2id?names%5B%5D=john HTTP/1.1
Host: example.com
Connection: Keep-Alive

有没有办法让框架不编码URL或其他一些解决这个问题?

Is there any way to make the framework NOT encode the URL, or some other way around this issue?

PS我不控制API,所以我不能改变它。

P.S. I do not control the API so I cannot change that.

更新:

这有点奇怪。我找到了一个解决方案,将我的C#代码更改为:

This is kinda wierd. I found a solution, changing my C# code to:

using (var client = new System.Net.WebClient())
{
    response = client.DownloadString(new Uri("http://example.com/name2id?names[]=john", true));
}

注意布尔 dontEscape 在乌里。它实际上已被弃用,但它有效吗?任何人都可以解释一下吗?

Note the boolean dontEscape in Uri. It is actually deprecated, but it works? Can anyone explain this?

推荐答案

如CodeInChaos所述,根据RFC2396,URL无效。

As mentioned by CodeInChaos, the URL is not valid according to RFC2396.

要使C#无法转义无效字符,URI的重载方法可以使用:

To make C# not escape invalid characters, the overloaded method of URI can be usen:

new Uri("http://example.com/name2id?names[]=john", true)

但是,这种方法已被弃用,但显然它仍然有效。我必须忍受警告弹出:)

However, this method is deprecated but apparently it still works. I have to live with the warning popping up :)

这篇关于防止C#在查询字符串中编码括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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