REST服务调用

时间:2015-10-14 12:37:53

标签: c# asp.net-mvc rest async-await

我必须使用REST服务调用方法,因为我从材料中获得了一些解决方案,但在await

中收到错误
public static Task RunAsync()
{
    string pathValue = WebConfigurationManager.AppSettings["R2G2APIUrl"];
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(pathValue);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

        var id = "12421";
        HttpResponseMessage response = await client.GetAsync("api/products/1");
        var jobid = new Jobs() { Job_ID = id};
        response = await client.PostAsJsonAsync("api/products", jobid);
        if (response.IsSuccessStatusCode)
        {
            Uri gizmoUrl = response.Headers.Location;
        }
    }
}
static void Main()
{
    RunAsync().Wait();
}

await在当前环境中不存在,因为我正在使用vs2010但是还有其他解决方案吗?

2 个答案:

答案 0 :(得分:1)

您可以使用await

,而不是使用ContinueWith
public static Task RunAsync()
{
    string pathValue = WebConfigurationManager.AppSettings["R2G2APIUrl"];
    var client = new HttpClient()
            client.BaseAddress = new Uri(pathValue);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
            var id = "12421";
        return client.GetAsync("api/products/1").ContinueWith(_ =>
    {
        var jobid = new Jobs() { Job_ID = id };
        return client.PostAsJsonAsync("api/products", jobid)
       .ContinueWith(responseTask =>
        {
          var gizmoUrl = responseTask.Result.IsSuccessStatusCode ?
                                        responseTask.Result.Headers.Location : null;
        });
    });
}

请注意,您的代码中存在一些冗余,例如发出GetAsync请求并且对返回的HttpResponseMessage不执行任何操作。

答案 1 :(得分:0)

也许你可以使用异步操作的.Result。

     public static Task RunAsync()
     {
        string pathValue = WebConfigurationManager.AppSettings["R2G2APIUrl"];
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(pathValue);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var id = "12421";
            HttpResponseMessage response = client.GetAsync("api/products/1").Result;
            var jobid = new Jobs() { Job_ID = id };
            response = client.PostAsJsonAsync("api/products", jobid).Result;
            if (response.IsSuccessStatusCode)
            {
                Uri gizmoUrl = response.Headers.Location;
            }
        }
    }