简体   繁体   English

带有字符串值C#的HttpClient发布

[英]HttpClient Post with string values c#

I am trying to post a request with following code, I have this code which fails (server complains bad request, as I have no control over server so dont know what server does.) 我正在尝试使用以下代码发布请求,但此代码失败(服务器抱怨请求错误,因为我无法控制服务器,因此不知道服务器的功能。)

private static readonly HttpClient client = new HttpClient();     
var values = new Dictionary<string, string>{
                    { "x", "value" }};
var content  = new FormUrlEncodedContent(values);
var response = await client.PostAsync(postUrl, content);

and then I have this code which works 然后我有这个代码可以正常工作

private static readonly HttpClient client = new HttpClient();     
var values = new Dictionary<string, string>{
                    { "x", "\"value\"" }};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync(postUrl, content);

Only difference is my value has extra "" around it. 唯一的区别是我的值周围带有多余的"" Can anyone please why it is happening? 有人可以请问为什么会这样吗? Or if I should have used something else? 还是我应该使用其他东西?

In the one that works, you are escaping the quotes. 在可行的方法中,您要转义引号。 That's what's enabling it work. 这就是使它起作用的原因。 It means that most likely the value is separated by a space. 这意味着该值很可能用空格分隔。 That is, it contains two words. 也就是说,它包含两个词。 Usually you have to do a url encode for the value or you just keep it in quotes. 通常,您必须对值进行网址编码,或者只是将其用引号引起来。 So when you escape the quotes with the /“ you are sending it to the server with the quotes hence it's working. 因此,当您使用“ /“对引号进行转义时,会将其与引号一起发送到服务器,从而可以正常工作。

Let's consider this sample program. 让我们考虑这个示例程序。

static void Main(string[] args)
{
    Show(new Dictionary<string, string> { { "x", "value" } });
    Show(new Dictionary<string, string> { { "x", "\"value\"" } });
}

private static async void Show(Dictionary<string, string> values)
{
    var content = new FormUrlEncodedContent(values);
    var body = await content.ReadAsStringAsync();
    Console.WriteLine(body);
}

The output is: x=value x=%22value%22 输出为: x=value x=%22value%22

In the first case when the server reads the body it sees x=value , and value is not a string. 在第一种情况下,服务器读取正文时,会看到x=value ,而value不是字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM