0

I am learning to use API and I have been given the specification of the URL, header and body of an API. The example is shown as follow

url: api/getRate
hearder:{
  "msgNo": "abc123",
  "receiver": "Customer_A"
}
body:{
  "dateTime": "2023/08/19 18:00:00",
  "Currency": "USD",
  "Ratetype": "COST"
}

How should I use C# method PostAsJsonAsync to get the result by this API?

Currently, I have the following code. Please tell me whether it is a correct way to use PostAsJsonAsync in the aforementioned situation.

var posturl = "api/getRate";
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("msgNo", "abc123");
httpClient.DefaultRequestHeaders.Add("receiver", "Customer_A");
var requestBody = new {
    "dateTime": "2023/08/19 18:00:00",
    "Currency": "USD",
    "Ratetype": "COST"};
var response = httpClient.PostAsJsonAsync(posturi, requestBody).Result;
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 1
    Have you tried your code and see whether it is workable or not? While I don't think the `requestBody` is correct as you are using anonymous type, it should be: `var requestBody = new { dateTime = "2023/08/19 18:00:00", /* Following properties */ };` – Yong Shun Aug 19 '23 at 04:53
  • My code is not workable. And I am curious how to set request hearder and request body before calling "PostAsJsonAsync()" – LeonJasonLu Aug 19 '23 at 05:14
  • What is the error, if any, that you get when compiling and/or executing that code. – rene Aug 19 '23 at 05:33
  • read this : https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-7.0 – Roozbeh Aug 19 '23 at 06:18

0 Answers0