简体   繁体   English

添加HttpClient PUT参数的正确方法? -将TypeScript REST调用移植到C#

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

I'm partially porting a TypeScript application to C#. 我将TypeScript应用程序部分移植到C#。 The application needs to perform a certain REST call on a webservice. 应用程序需要在Web服务上执行特定的REST调用。 The webservice is written in C# and the specific method has the following signature: Web服务是用C#编写的,特定方法具有以下签名:

public async Task<IHttpActionResult> RegisterDevice(DeviceRegistration deviceRegistration)

The original application (TypeScript) makes the REST call in the following manner: 原始应用程序(TypeScript)通过以下方式进行REST调用:

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. 我在StackOverflow上搜索了如何进行调用,并找到了说明操作方法的帖子。 I then created the following in the C# version: 然后,我在C#版本中创建了以下代码:

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 ? 我在想FormUrlEncodedContent吗? What is the correct way of doing this call in C#? 用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;
}

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);

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

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