Click here to Skip to main content
15,889,825 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am calling a web service from MVC controller to post data. Both stays in same solution.

My code in Web Api is:

[HttpPost]
        public IHttpActionResult InsertUsers([FromBody]tblUserAgentSubAgentVMWithByte tblUserAgentSubAgentVM)
        {    return Ok("Success");    }
My code of controller to call web api is :
public ViewResult Register(tblUserAgentSubAgentVM tblUserAgentSubAgentVM)
        {
            using (var client = new HttpClient())
            {
                string apiHost = "http://localhost:51522";
                client.BaseAddress = new Uri(apiHost);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var json = JsonConvert.SerializeObject(tblUserAgentSubAgentVMWithByte);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var result1 = client.PostAsync("api/Users/InsertUsers", content);
            }
        }
when code goes to client.PostAsync("api/Users/InsertUsers", content);, I am getting message "Id = 59, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"

Why is object not being posted to API?
How can I solve the issue?

What I have tried:

Found from some article that I can not mix mix async and synchronous code like this. PostAsyn seems to be async. But I have no clue on how to not use it and call API.
Posted
Updated 22-Feb-19 2:15am
v2
Comments

1 solution

Your question itself has the answer, your task has not yet been evaluated—Result = "{Not yet computed}. You need to give it more time, and check the result later. This time won't be known to you, since it is undefined amount of time.

That is because in the synchronous code you need to wait for the tasks yourself. So to say, the code becomes,
var json = JsonConvert.SerializeObject(tblUserAgentSubAgentVMWithByte);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var result1 = client.PostAsync("api/Users/InsertUsers", content).Result;
Now, the result1 will contain the result of the request. Note that this will be a blocking call, so the thread will remain blocked—in waiting state—until your request is processed, and the response is captured.

The problem is, this is not an approach that I can recommend. Although you can mix sync and async code, and it is totally valid. Think of this,
C#
// Capture asynchronously. 
var people = dbContext.GetPeople().Where(person => /* some filter */).ToListAsync();;

// Assuming, it is a small buffer of people, go sync
foreach (var person in people) {
   // Do something
}

// Save asynchronously.
dbContext.SaveAsync();
The benefit of this is, that where you know there is a delay, take the job in the background, but in the cases where a context switch is more expensive, I recommend that you stay in the same thread, do the task and generate the response.

For this sake, I recommend that you continue to use the async patterns, and write the code in async fashion.
C#
// Change the signature
public async Task<ViewResult> Register(tblUserAgentSubAgentVM tblUserAgentSubAgentVM)
{
    using (var client = new HttpClient())
    {
        string apiHost = "http://localhost:51522";
        client.BaseAddress = new Uri(apiHost);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var json = JsonConvert.SerializeObject(tblUserAgentSubAgentVMWithByte);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        // Let the runtime unwrap the task for you!
        var result1 = await client.PostAsync("api/Users/InsertUsers", content);

        // Generate and return the result
    }
}
This way, now your runtime will automatically manage these tasks. Since you are using ASP.NET, it is way better and scalable to use async functions, than to bind the requests to threads. This is expensive. Please, do not do this.
 
Share this answer
 
v2
Comments
Codes DeCodes 22-Feb-19 12:19pm    
Thanks for your time to reply me in such a descriptive way. Made me all clear.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900