为什么我的Web api客户端调用在Raspberry Pi2 Iot中不起作用 [英] why does my web api client call not work in Raspberry Pi2 Iot

查看:104
本文介绍了为什么我的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中,它不起作用. 但是,当我从Web API服务器(在Iot中)调用Get时,它可以正常工作. ?

In C# desktop app it works. In Windows 10 IoT on a Raspberry Pi2 device it does not work. Yet, when i am calling a Get from my Web API server *in Iot) it works fine. ?

推荐答案

我现在使用此代码已有一年,并且有效:

I am using this code for a year now and it works:

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

这篇关于为什么我的Web api客户端调用在Raspberry Pi2 Iot中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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