无法从MVC控制器发布到web api [英] Not able to post from MVC controller to web api

查看:78
本文介绍了无法从MVC控制器发布到web api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从MVC控制器调用Web服务来发布数据。两者都保持相同的解决方案



我在Web Api中的代码是:



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

我调用web api的控制器代码是:

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

当代码转到client.PostAsync(api / Users / InsertUsers,content);时,我收到消息Id = 59,Status = WaitingForActivation, Method ={null},Result ={Not yet computed}



为什么没有将对象发布到API?

我该如何解决这个问题呢?



我的尝试:



从一些文章中发现我不能混合混合异步和同步代码这样.PostAsyn似乎是异步的。但我不知道如何不使用它并调用API。

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.

推荐答案

您的问题本身有答案,您的任务尚未评估 - 结果={尚未计算} 。你需要给它更多的时间,并在以后检查结果。你不会知道这个时间,因为它是不确定的时间量。



这是因为在同步代码中你需要等待你自己的任务。所以说,代码变成,

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;

现在,result1将包含请求的结果。请注意,这将是一个阻塞调用,因此线程将保持阻塞状态 - 直到您的请求被处理,并且捕获响应。



问题是,这不是我推荐的方法。虽然您可以混合同步和异步代码,但它完全有效。想一想,

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,

// 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.

// 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
    }
}

这样,现在您的运行时将自动管理这些任务。由于您使用的是ASP.NET,因此使用异步函数比将请求绑定到线程更好,更具伸缩性。这很贵。请不要这样做。

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.


这篇关于无法从MVC控制器发布到web api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆