user30646 user30646 - 1 year ago 176
C# Question

getting 'Bad Request' from PutAsJsonAsync

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}");
log.Info($"Response Status Code: {response.Headers} | Reason : {response.ReasonPhrase}");


Answer Source

Try using client.PutAsync() instead of client.PutAsJsonAsync()

I would call it like this:

client.PutAsync("xxx/xx/xxx",new StringContent(myQueueItem, UnicodeEncoding.UTF8, "application/json")).Result
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download