0

Lets say I have Employee object coming from client via Post and we receive it in Webapi via [FromBody] attribute.

May I know, how to transfer this object by converting to Json again and posting it to another webapi? The response from this will be integer value. Which I will sending back to the client.

Also, I am trying to make this as Asynchronous.

I tried searching various sites and posts for hours and could not reach to a solution.

Appreciate your help :) Thanks.

[HttpPost]
public Task<ActionResult<int>> GetValue([FromBody] Employee emp)
{
}
  • _"May I know, how to transfer this object by converting to Json again and posting it to another webapi?"_ - have you done any research on this? Sending an object via JSON is an incredibly common task, so there are many existing questions on this site doing exactly this. – Llama Sep 04 '19 at 02:56
  • Yes John I did my research, I understand, back in the days I even tried using DataContractJsonSerializer in WCF and it used to work fine. I tried few things but those assemblies are not compatible in Web Api project. I am clueless. I tried something like this, using (var client = new HttpClient()) { var mediaType = new MediaTypeHeaderValue("application/json"); var jsonserializerSettings = new JsonSerializerSettings(); JsonNetFormatter won't resolve -- > //var jsonFormatter = new JsonNetFormatter(jsonserializerSettings.Add()); – OptimusPrime Sep 04 '19 at 03:01
  • The first Google result for the query _"how to post JSON to a server in C#"_ yields [this question](https://stackoverflow.com/questions/9145667/how-to-post-json-to-a-server-using-c), from which I reckon [this is a good answer](https://stackoverflow.com/a/49266816/3181933). Note the section comment about using HttpClientFactory instead of `using (var client = new HttpClient())` everywhere. – Llama Sep 04 '19 at 03:03
  • No John, perhaps you are right, I am looking for using client.PostAsync method example. I will be using the Task> here – OptimusPrime Sep 04 '19 at 03:10

1 Answers1

0

You can use Newtonsoft.Json to convert object into json.

using Newtonsoft.Json;

var jsonString = JsonConvert.SerializeObject(emp);

Then you call your external web api using httpClient or use HttpClientFactory

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("url");
    var result = await client.PostAsync("/endpoint", jsonString);

    // use below as you want
    string resultContent = await result.Content.ReadAsStringAsync();
}
cdev
  • 3,443
  • 1
  • 23
  • 28