【问题标题】:httpClient show me error c# winformhttpClient 显示错误 c# winform
【发布时间】:2016-05-12 18:35:18
【问题描述】:

我有以下代码,但它显示错误我使用的是框架 4.5。请帮忙。

var baseAddress = new Uri("http://private-5e199-karhoofleetintegration.apiary-mock.com/");

using (var httpClient = new HttpClient { BaseAddress = baseAddress })
{
    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept-charset", "utf-8");

    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("authorization", "Basic *sample_token*");

    using (var content = new StringContent("{  \"vehicles\": [    {      \"vehicle_type\": \""+ vehicale_type +"\",      \"vehicle_id\": \"" +vehicle_id+"\",  "\"heading\": 90      }    }  ]}", System.Text.Encoding.Default, "application/json"))
    {
        using (var response = await httpClient.PostAsync("{supplier_id}/availability?version=2", content))
        {
            string responseData = await response.Content.ReadAsStringAsync();
        }
    }
}

【问题讨论】:

  • 您是否将您的方法标记为async? (例如:public async void my_method())。
  • await 运算符只能与异步方法一起使用
  • no..我正在使用简单的方法并显示其上面的代码
  • 使方法异步并返回 Task 或 Task
  • 怎么样?到异步方法

标签: c# winforms dotnet-httpclient


【解决方案1】:

要使用 async/await 内容,您需要使用 async 关键字标记您的方法。

如果您的方法是事件处理程序,则使用async void,如果不是,则使用async Taskasync Task<ReturnType>。 (确保将“ReturnType”替换为您的方法返回的实际类型)

示例:

public async Task GetDataFromTheWeb()
//     ^^^^^ add this keyword
{
    var baseAddress = new Uri("http://private-5e199-karhoofleetintegration.apiary-mock.com/");

    using (var httpClient = new HttpClient { BaseAddress = baseAddress })
    {
        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept-charset", "utf-8");

        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("authorization", "Basic *sample_token*");

        using (var content = new StringContent("{  \"vehicles\": [    {      \"vehicle_type\": \""+ vehicale_type +"\",      \"vehicle_id\": \"" +vehicle_id+"\",  "\"heading\": 90      }    }  ]}", System.Text.Encoding.Default, "application/json"))
        {
            using (var response = await httpClient.PostAsync("{supplier_id}/availability?version=2", content))
            {
                string responseData = await response.Content.ReadAsStringAsync();
            }
        }
    }
}

【讨论】:

  • 没问题。如果此答案解决了您的问题,那么您可以将其标记为已接受。编码愉快!
猜你喜欢
  • 2017-05-26
  • 1970-01-01
  • 1970-01-01
  • 2015-01-08
  • 2017-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多