response.Content.ReadAsStringAsync没有读取所有数据

问题描述 投票:0回答:2

我有一个azure函数,它使用基本身份验证调用Rest API。服务器的响应是好的,但是我只有从响应中接收部分数据的问题 - 一些字段返回为null。

我正在使用httpclient进行其余的API调用。这是我的代码:

  using (var client = new HttpClient())
        {

            var webUrl = "https://api.livechatinc.com/chats/XXXXXX";

            client.BaseAddress = new Uri(webUrl);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var user = "XXXXXXXXXX";
            var password = "XXXXXXXXX";
            var base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{user}:{password}"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64String);

            HttpResponseMessage response   = await client.GetAsync(webUrl);
            response.EnsureSuccessStatusCode();

            //Only getting partial information
            string jsonString = await response.Content.ReadAsStringAsync();

            //Deserialise JSON
            Chat responseData = JsonConvert.DeserializeObject<Chat>(jsonString);

        }

当我运行我的azure函数调试器时,我可以证明我得到了我期望的URL数据的空字段。

enter image description here

请注意,responseData字段在反序列化后显示ChatStartUrl的空值。

这是因为该字段未从响应内容返回。

我已经确定它不是我的数据合同和JSON.net反序列化。我的数据合同是:

 public  class Chat
{
    [JsonProperty("type")]
    public string Type { get; set; }

    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("tickets")]
    public Ticket[] Tickets { get; set; }

    [JsonProperty("visitor_name")]
    public string VisitorName { get; set; }

    [JsonProperty("visitor_id")]
    public string VisitorId { get; set; }

    [JsonProperty("visitor_ip")]
    public string VisitorIp { get; set; }

    [JsonProperty("visitor")]
    public Visitor Visitor { get; set; }

    [JsonProperty("agents")]
    public Agent[] Agents { get; set; }

    [JsonProperty("supervisors")]
    public object[] Supervisors { get; set; }

    [JsonProperty("rate")]
    public string Rate { get; set; }

    [JsonProperty("duration")]
    public long Duration { get; set; }

    [JsonProperty("chat_start_url")]
    public Uri ChatStartUrl { get; set; }

    [JsonProperty("referrer")]
    public Uri Referrer { get; set; }

    [JsonProperty("group")]
    public long[] Group { get; set; }

    [JsonProperty("started")]
    public string Started { get; set; }

    [JsonProperty("custom_variables")]
    public object[] CustomVariables { get; set; }

    [JsonProperty("pending")]
    public bool Pending { get; set; }

    [JsonProperty("tags")]
    public object[] Tags { get; set; }

    [JsonProperty("timezone")]
    public string Timezone { get; set; }

    [JsonProperty("greeting")]
    public Greeting Greeting { get; set; }

    [JsonProperty("messages")]
    public Event[] Messages { get; set; }

   /* [JsonProperty("prechat_survey")]
    public PrechatSurvey[] PrechatSurvey { get; set; }*/

    [JsonProperty("events")]
    public Event[] Events { get; set; }

    [JsonProperty("engagement")]
    public string Engagement { get; set; }

    [JsonProperty("started_timestamp")]
    public long StartedTimestamp { get; set; }

    [JsonProperty("ended_timestamp")]
    public long EndedTimestamp { get; set; }

    [JsonProperty("ended")]
    public string Ended { get; set; }
}

public  class Agent
{
    [JsonProperty("display_name")]
    public string DisplayName { get; set; }

    [JsonProperty("email")]
    public string Email { get; set; }

    [JsonProperty("ip")]
    public string Ip { get; set; }
}

public  class Event
{
    [JsonProperty("author_name", NullValueHandling = NullValueHandling.Ignore)]
    public string AuthorName { get; set; }

    [JsonProperty("text")]
    public string Text { get; set; }

    [JsonProperty("message_json", NullValueHandling = NullValueHandling.Ignore)]
    public string MessageJson { get; set; }

    [JsonProperty("date")]
    public string Date { get; set; }

    [JsonProperty("timestamp")]
    public long Timestamp { get; set; }

    [JsonProperty("agent_id", NullValueHandling = NullValueHandling.Ignore)]
    public string AgentId { get; set; }

    [JsonProperty("user_type")]
    public string UserType { get; set; }

    [JsonProperty("type")]
    public string Type { get; set; }

    [JsonProperty("welcome_message", NullValueHandling = NullValueHandling.Ignore)]
    public bool? WelcomeMessage { get; set; }

    [JsonProperty("event_type", NullValueHandling = NullValueHandling.Ignore)]
    public string EventType { get; set; }
}

public  class Greeting
{
    [JsonProperty("id")]
    public long Id { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }
}


public  class Ticket
{
    [JsonProperty("id")]
    public string Id { get; set; }
}

public  class Visitor
{
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("email")]
    public string Email { get; set; }

    [JsonProperty("ip")]
    public string Ip { get; set; }

    [JsonProperty("city")]
    public string City { get; set; }

    [JsonProperty("region")]
    public string Region { get; set; }

    [JsonProperty("country")]
    public string Country { get; set; }

    [JsonProperty("country_code")]
    public string CountryCode { get; set; }

    [JsonProperty("timezone")]
    public string Timezone { get; set; }

    [JsonProperty("user_agent")]
    public string UserAgent { get; set; }
}

有趣的是,其余的api在Postman中工作正常,我可以获得所有数据。

这是我从邮递员的反应中得到的

{
"type": "chat",
"id": "PPTE7XI3AQ",
"tickets": [
    {
        "id": "DJWKT"
    }
],
"visitor_name": "Rupinder Kaur",
"visitor_id": "S1552009602.e395581450",
"visitor_ip": "49.183.59.243",
"visitor": {
    "id": "S1552009602.e395581450",
    "name": "Rupinder Kaur",
    "email": "[email protected]",
    "ip": "49.183.59.243",
    "city": "Abbotsford",
    "region": "Victoria",
    "country": "Australia",
    "country_code": "AU",
    "timezone": "Australia/Victoria",
    "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"
},
"agents": [
    {
        "display_name": "David",
        "email": "[email protected]",
        "ip": "203.30.93.14"
    }
],
"supervisors": [],
"rate": "not_rated",
"duration": 357,
"chat_start_url": "https://wiise.com/au/explore/detailed-accounting/?utm_source=googlewiise&utm_medium=paidsearch&utm_campaign=Wiise&gclid=EAIaIQobChMI3ZrLuqG14QIVBR2PCh0VIAb7EAAYASAAEgKkWPD_BwE",
"referrer": "https://www.google.com/",
"group": [
    0
],
"started": "Thu, 04/04/19 12:25:43 pm",
"custom_variables": [],
"pending": false,
"tags": [],
"timezone": "Australia/Sydney",
"greeting": {
    "id": 7991,
    "name": "Invite after 360 seconds"
},
"messages": [
    {
        "author_name": "David",
        "text": "Hi there :) \n\nThank you for checking out our website, how can I help?",
        "message_json": "",
        "date": "Thu, 04/04/19 12:25:43 pm",
        "timestamp": 1554341143,
        "agent_id": "[email protected]",
        "user_type": "agent",
        "type": "message",
        "welcome_message": true
    },
    {
        "author_name": "Rupinder Kaur",
        "text": "hi there",
        "message_json": "",
        "date": "Thu, 04/04/19 12:25:54 pm",
        "timestamp": 1554341154,
        "user_type": "visitor",
        "type": "message"
    },
    {
        "author_name": "Rupinder Kaur",
        "text": "I would like to trial it",
        "message_json": "",
        "date": "Thu, 04/04/19 12:26:01 pm",
        "timestamp": 1554341161,
        "user_type": "visitor",
        "type": "message"
    },
    {
        "author_name": "Rupinder Kaur",
        "text": "I am mainly looking for cashflow reports",
        "message_json": "",
        "date": "Thu, 04/04/19 12:26:25 pm",
        "timestamp": 1554341185,
        "user_type": "visitor",
        "type": "message"
    }
],
"prechat_survey": [
    {
        "key": "Name:",
        "value": "xxxxxx",
        "id": "2001"
    },
    {
        "key": "E-mail:",
        "value": "xxxxxx",
        "id": "2002"
    }
],
"events": [
    {
        "author_name": "David",
        "text": "Hi there :) \n\nThank you for checking out our website, how can I help?",
        "message_json": "",
        "date": "Thu, 04/04/19 12:25:43 pm",
        "timestamp": 1554341143,
        "agent_id": "[email protected]",
        "user_type": "agent",
        "type": "message",
        "welcome_message": true
    },
    {
       "author_name": "XXXXXX",
        "text": "XXXXXXXXXX",
        "message_json": "",
        "date": "Thu, 04/04/19 12:25:54 pm",
        "timestamp": 1554341154,
        "user_type": "visitor",
        "type": "message"
    },
    {
        "author_name": "XXXXXX",
        "text": "XXXXXXXXXX",
        "message_json": "",
        "date": "Thu, 04/04/19 12:26:01 pm",
        "timestamp": 1554341161,
        "user_type": "visitor",
        "type": "message"
    },
    {
        "author_name": "XXXXXX",
        "text": "XXXXXXXXXX",
        "message_json": "",
        "date": "Thu, 04/04/19 12:26:25 pm",
        "timestamp": 1554341185,
        "user_type": "visitor",
        "type": "message"
    },
    {
        "text": "Rupinder Kaur left the chat.",
        "date": "Thu, 04/04/19 12:31:40 pm",
        "timestamp": 1554341500,
        "type": "event",
        "event_type": "closed",
        "user_type": "visitor"
    }
],
"engagement": "auto_invite",
"started_timestamp": 1554341143,
"ended_timestamp": 1554341500,
"ended": "Thu, 04/04/19 12:31:40 pm"}

我试过deserialisaing从Postman返回的内容,我得到没有空字段的所有数据

//This works
var testJSON = System.IO.File.ReadAllText(@"C:\temp\ChatSchema.json");
Chat responseData = JsonConvert.DeserializeObject<Chat>(testJSON);

所以我怀疑Content.ReadAsStringAsync函数没有按预期工作。

我尝试了以下内容并仍然遇到了同样的问题:

       var buffer = await response.Content.ReadAsByteArrayAsync();
       var responseString = Encoding.UTF8.GetString(buffer, 0, buffer.Length);

       string content = responseString;
       Chat des = JsonConvert.DeserializeObject<Chat>(content);
azure async-await json.net httpclient azure-functions
2个回答
0
投票

读取原始文本,然后将其反序列化为模型类。我还必须更改序列化例程以保存为'UTF-8'。

你可以参考下面的代码:

var stream = response.Content.ReadAsStreamAsync().Result;
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();

string content = text;
string des = JsonConvert.DeserializeObject<Chat>(content);

0
投票

刚刚解决了我的问题!

我不得不添加自定义标头,因为LiveChat需要它:

 client.DefaultRequestHeaders.Add("X-API-Version", "2");

现在我收到包括Uri数据在内的所有信息!

感谢所有回复。

© www.soinside.com 2019 - 2024. All rights reserved.