为什么我的web api客户端调用在Raspberry Pi2 Iot中不起作用

时间:2015-11-01 17:20:02

标签: c# client asp.net-web-api raspberry-pi2 iot

我有这段代码:

private const string route = "/api/Print";
public bool Update(string header, string tc)
{
    bool success = false;
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("my uri");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var print = new Print { CompanyRef = new Guid(), Header = header, TC = tc };
        var response = client.PutAsJsonAsync(route, print);
    }
    success = true;

    return success;
}

public sealed class Print
{
    public string Header { get; set; }
    public string TC { get; set; }
    public System.Guid CompanyRef { get; set; }
}

我称之为:

Update(" header", " string tc");

在C#桌面应用程序中,它可以运行。 在Raspberry Pi2设备上的Windows 10 IoT中,它不起作用。 然而,当我在Iot中调用来自我的Web API服务器*的Get时,它工作正常。 ?

1 个答案:

答案 0 :(得分:1)

我现在使用此代码已有一年了,它的确有效:

    using Windows.Web.Http;


    using (HttpClient httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
        try
        {
            var o = new
            {
                operation = "NewEvent",
                location_id = locationID,
                eventName = eventName
            };

            HttpStringContent content = new HttpStringContent(JsonConvert.SerializeObject(o), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");

            HttpResponseMessage response = await httpClient.PostAsync(new Uri(urlPostData), content);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            // TODO: Do something with the responseBody
        }
        catch (Exception)
        {
            // TODO: Deal with exception - could be a server not found, 401, 404, etc.
        }
    }