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)
{
}
4
  • "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. Commented Sep 4, 2019 at 2: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()); Commented Sep 4, 2019 at 3:01
  • The first Google result for the query "how to post JSON to a server in C#" yields this question, from which I reckon this is a good answer. Note the section comment about using HttpClientFactory instead of using (var client = new HttpClient()) everywhere. Commented Sep 4, 2019 at 3:03
  • No John, perhaps you are right, I am looking for using client.PostAsync method example. I will be using the Task<ActionResult<int>> here Commented Sep 4, 2019 at 3:10

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Mate, that's not correct, jsonstring is not HttpContent, in PostAsync, Httpcontent object is expected as second parameter.
@OptimusPrime kindly mention the correct way.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.