在MVC操作方法中调用http帖子?

时间:2015-09-30 19:51:07

标签: c# asp.net-mvc-4 dotnet-httpclient

我使用HttpClient在操作方法中调用POST,但我不确定它是否正确完成。我不需要它是异步的。基本上,如果在我的系统上成功创建了用户,我会在另一个系统中创建它们。这是我打电话的代码:

 using (var client = new HttpClient())
        {
            var postData = new FormCollection();
            postData["api_token"] = ConfigurationManager.AppSettings["ApiToken"];
            postData["api_action"] = "Save";
            postData["customer_email"] = userName;
            postData["customer_password"] = password;
            var result = client.PostAsync(string.Format("{0}/api", ConfigurationManager.AppSettings["Url"]), content).Result;

            var xmlResponse = result.Content.ReadAsStringAsync().Result;

}

1 个答案:

答案 0 :(得分:1)

以下两行:

var result = client.PostAsync(string.Format("{0}/api", ConfigurationManager.AppSettings["Url"]), content).Result;

var xmlResponse = result.Content.ReadAsStringAsync().Result;

应重构为以下内容:

var result = await client.PostAsync(string.Format("{0}/api", ConfigurationManager.AppSettings["Url"]), content);

var xmlResponse = await result.Content.ReadAsStringAsync();

您必须使用await,否则您将阻止在异步方法结束时调用Result的线程。此外,您要忘记相应的操作应该返回Task<ActionResult>

public async Task<ActionResult> ActionName()