从PutAsJsonAsync获取“错误请求" [英] getting 'Bad Request' from PutAsJsonAsync

查看:365
本文介绍了从PutAsJsonAsync获取“错误请求"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing Azure Queue Trigger function app that picks up data from a message queue and upload them to a storage, that provides REST service, using PUT request. For test purpose, I'm providing test data inside request body field on Azure interface instead of picking data from the queue. I'm using PutAsJsonAsync to consume REST. The problem is I'm getting Bad Request error. I validated JSON structure using validation tool and it is valid. And I also uploaded the same data successfully using Postman. So I'm guessing it maybe that problem is in my code. Here's my code :

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

这篇关于从PutAsJsonAsync获取“错误请求"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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