EpicSam EpicSam - 12 days ago 5
reST (reStructuredText) Question

Correct way of adding HttpClient PUT parameters? - Porting TypeScript REST call to C#

I'm partially porting a TypeScript application to C#. The application needs to perform a certain REST call on a webservice. The webservice is written in C# and the specific method has the following signature:

public async Task<IHttpActionResult> RegisterDevice(DeviceRegistration deviceRegistration)


The original application (TypeScript) makes the REST call in the following manner:

this.$http.put(this.Configuration.registrationEndpointUrl, {
field1: value1,
field2: value2,
field3: value3
})


I searched StackOverflow on how to do the call and found a post explaining how to do it. I then created the following in the C# version:

var pairs = new List<KeyValuePair<string, string>>() {
new KeyValuePair<string, string>("field1", Settings.Value1),
new KeyValuePair<string, string>("field2", Settings.Value2),
new KeyValuePair<string, string>("field3", "value3")
};
var content = new FormUrlEncodedContent(pairs);
var response = await Client.PutAsync(Configuration.RegistrationUrl, content);


However this just returns an empty response. I'm thinking something is wrong with the
FormUrlEncodedContent
? What is the correct way of doing this call in C#?

EDIT: Client initialisation code:

private static async Task<HttpClient> CreateClient() {
await Authenticator.VerifyAuthentication();
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("x-zumo-auth", Settings.OAuthToken);
client.DefaultRequestHeaders.Add("x-oauth-provider", Settings.OAuthProvider.Value.ToString());
return client;
}

Answer

Instead of using the method

var response = await Client.PutAsync(Configuration.RegistrationUrl, content);

You can use this

var response = await Client.PutAsJsonAsync(Configuration.RegistrationUrl, content);