c# - 从 PutAsJsonAsync 获取 'Bad Request'

标签 c# azure azure-functions

我正在编写 Azure 队列触发器功能应用程序,该应用程序使用 PUT 请求从消息队列中获取数据并将其上传到提供 REST 服务的存储。出于测试目的,我在 Azure 界面上的请求正文字段内提供测试数据,而不是从队列中选取数据。我正在使用 PutAsJsonAsync 来使用 REST。问题是我收到错误请求错误。我使用验证工具验证了 JSON 结构,它是有效的。我也使用 Postman 成功上传了相同的数据。所以我猜测问题可能出在我的代码中。这是我的代码:

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;  

public static void Run(string myQueueItem, TraceWriter log)
{
    string URL = "<url>"; 
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(URL);

    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Add("token","<token value>");

    HttpResponseMessage response = client.PutAsJsonAsync("xxx/xx/xxx",myQueueItem).Result;

    if (response.IsSuccessStatusCode)
    {
        string responseString = response.Content.ReadAsStringAsync().Result;
        log.Info($"This is result: {responseString}");
    }
    else
    {
        log.Info($"Response Status Code: {response.Headers} | Reason : {response.ReasonPhrase}");
    }  


}

最佳答案

尝试使用 client.PutAsync() 而不是 client.PutAsJsonAsync()

我会这样调用它:

client.PutAsync("xxx/xx/xxx",new StringContent(myQueueItem, UnicodeEncoding.UTF8, "application/json")).Result

关于c# - 从 PutAsJsonAsync 获取 'Bad Request',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38795476/

相关文章:

c# - 可访问性级别对性能或速度的影响?

c# - 更改此条件,使其不总是计算为 'true'

azure - 在 Azure 中创建 VM 时,虚拟网络可以位于不同的资源组中吗

azure - 在需要提升权限的 Azure WebJob 中运行脚本

azure - 如何在.net core api中实现LaunchDarkly功能管理

c# - T4 工具箱 Linq2Sql

Azure函数+nodejs+vscode : launch config to debug multiple azure function funcs?

azure - 如何通过代码直接访问Azure On-Prem数据网关

azure - 如何使用 Azure 事件网格将多个存储帐户事件连接到一个函数

c# - HasDbFunction,没有映射实体类的表值函数