简体   繁体   English

如何将布尔正文发送到 HttpClient.PutAsync 或 HttpClient.PostAsync?

[英]How can I send a boolean body to HttpClient.PutAsync or HttpClient.PostAsync?

I am trying to invoke a PUT service that accepts a single boolean value as a body.我正在尝试调用接受单个布尔值作为主体的PUT服务。 The service works when I test it from Javascript or Swagger, but it rejects my request from .NET.当我从 Javascript 或 Swagger 测试它时,该服务可以工作,但它拒绝了我从 .NET 发出的请求。

This works (Javascript):这有效(Javascript):

fetch(URL, {
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `bearer ${TOKEN}`
    },
    method: 'PUT',
    body: true,
});

This does not work (.NET):这不起作用(.NET):

private static async Task<string> RunTest(bool b)
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {TOKEN}");
        var content = new StringContent(b.ToString(), Encoding.UTF8, "application/json");
        HttpResponseMessage result = await client.PutAsync(URL, content);
        return result.ToString();
    }
}

The server is returning a 400 for my .NET request.服务器为我的 .NET 请求返回400 But as I said, it works when I test using fetch or other ways.但正如我所说,当我使用fetch或其他方式进行测试时,它是有效的。 So I assume I am doing something wrong in .NET.所以我假设我在 .NET 中做错了什么。

How can I pass a boolean body to HttpClient.PutAsync ?如何将布尔主体传递给HttpClient.PutAsync

As @Nkosi suggested in the comments, I needed to serialize the boolean to JSON instead of just calling ToString .正如@Nkosi 在评论中所建议的那样,我需要将布尔值序列化为 JSON 而不仅仅是调用ToString

The problem appears to be that ToString produces upper-case values of True or False , instead of the expected lower-case values of true or false .问题似乎是ToString产生TrueFalse大写值,而不是预期的小写值truefalse

So I added a reference to Json.NET and changed the code to this:所以我添加了对Json.NET的引用并将代码更改为:

private static async Task<string> RunTest(bool b)
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {TOKEN}");
        var content = new StringContent(JsonConvert.SerializeObject(b), Encoding.UTF8, "application/json");
        HttpResponseMessage result = await client.PutAsync(URL, content);
        return result.ToString();
    }
}

This works.这有效。

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

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